问题
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 Interface
s, 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