是否可以序列化分组列表? [英] Is it possible to serialize a grouped list?

查看:103
本文介绍了是否可以序列化分组列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要序列化分组列表.但是我出错了.是否可以序列化分组列表?如果是,那么如何?

I want to serialize grouped list. but I am getting error. Is it possible to serialize a grouped list? if yes then How?

错误:

Cannot serialize interface System.Linq.IGrouping`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[MyProject.MyNamespace.Elements, MyProject.MyNamespace, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].

代码:

MemoryStream memoryStream = new MemoryStream();
List<IGrouping<string, Elements>> lstGroupedElements = listElements.GroupBy(member=> member.Type).ToList();               
XmlSerializer objXmlSerializer = new XmlSerializer(typeof(List<IGrouping<string, Elements>>));
objXmlSerializer.Serialize(memoryStream, lstGroupedElements);

推荐答案

您无法序列化Interface,因为无法恢复它们.对于反序列化,将需要new IGrouping()之类的东西,而这是不可能的.因此,您必须构建自己的分组结构,其中包含分组名称及其元素.

You can’t serialize Interfaces, because there is no way to restore them. For the Deserialization something like new IGrouping() would be needed and that’s not possible. So you have to build your own Grouping Structure, which holds the group name and its elements.

listElements.GroupBy(member=> member.Type)
            .Select(g => new MyGrouping() {GroupName = g.Key, Elements = g.ToList()})
            .ToList();

MyGrouping可能如下所示:

MyGrouping could look like this:

public class MyGrouping
{
    public string GroupName { get; set; }

    public List<Element> Elements { get; set; }
}

,或者当您想要扁平化的XML实现某些接口时:

or when you want a flattened XML implement some Interfaces:

public class MyGrouping : Collection<Element>, IGrouping<string, Element>
{
    …
}

这篇关于是否可以序列化分组列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆