Merging List<> and mainting identity
I have 3 .net Lists items, I need to merge them all into one, to o开发者_如何学Gorder them and bind them to a datagrid. However, I need a way of indicating which original list each item came from, so that I can identify this in the datagrid (change color or font etc).
Can anyone suggest the best way to do this?
List<Foo> list1 = new List<Foo>();
List<Foo> list2 = new List<Foo>();
List<Foo> list3 = new List<Foo>();
var query = list1.Select(foo => new { foo, list = "list1" })
.Concat(list2.Select(foo => new { foo, list = "list2" }))
.Concat(list3.Select(foo => new { foo, list = "list3" }))
.OrderBy(item => item.foo); // whatever you need to order by
Expand the properties as needed.
Assuming that your lists contains items of classes that you can amend I'd suggest that you add a property to those classes that keeps track of which type of the 3 it is. Either as an enum
or possibly a reference to the actual list
that contained it if you might need to refer back.
If you're not able to do that but assuming that they do contain a name property or similar and it's a readonly grid, a very ugly way would be to add a specific prefix/postfix to the name that says where it came from and then just remove that prefix/postfix before showing it on the screen.
Simple solution, assuming you don't want to modify the original class, or it's a primitive, you can use anonymous types:
var resultList = list1.Select(value => new {value, list = list1}) .Concat(list2.Select(value => new {value, list = list2}) .Concat(list3.Select(value => new {value, list = list3}))) .ToList();
I'd go with something like this:
List<object> list1 = new List<object>();
List<object> list2 = new List<object>();
List<object> list3 = new List<object>();
List<KeyValuePair<int, object>> mergedList = new List<KeyValuePair<int, object>>();
mergedList.AddRange(list1.Select(obj => new KeyValuePair<int, object>(1, obj)));
mergedList.AddRange(list2.Select(obj => new KeyValuePair<int, object>(2, obj)));
mergedList.AddRange(list3.Select(obj => new KeyValuePair<int, object>(3, obj)));
The better solution though, would be to add a property to your object that is some kind of enumeration that tells you something about the object itself. The lists themselves are metadata of some sort - list1 is a list of X, not just a list, so all of it's elements should have some kind of notion of X.
精彩评论