Is it possible to serialize a grouped list?

早过忘川 提交于 2020-01-13 20:35:07

问题


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

Error :

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]].

Code :

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);

回答1:


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();

Edit:

MyGrouping could look like this:

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

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

or when you want a flattened XML implement some Interfaces:

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


来源:https://stackoverflow.com/questions/24926717/is-it-possible-to-serialize-a-grouped-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!