Grouping objects using linq or lambda expression

I have a list of objects that I want to convert to another list of objects.

The first object is as follows:

private class ObjectOne { public string Name { get; set; } public string Item{ get; set; } } 

And one more such

 public class ObjectTwo { public string Name { get; set; } public IEnumerable<string> Items{ get; set; } } 

I would like to write a linq query or a lambda expression that can convert an ObjectOne data list to an ObjectTwo data list. Each element in the ObjectTwo list will contain a different name from ObjectOne and there will be an enumeration of all elements associated with this name.

For example, the following list of ObjectOne data

 "Name One", "Item One" "Name One", "Item Two" "Name Two", "Item Three" 

will create the following ObjectTwo list:

 "Name One", {"Item One", "Item Two"} "Name Two", {"Item Three"} 
+7
source share
2 answers

Use the GroupBy Linq statement. Then, for each group, select the Key (the one that you used to group), and convert the elements of each group to a List.

 var oneList = new List<ObjectOne> { new ObjectOne {Name = "Name One", Item = "Item One"}, new ObjectOne {Name = "Name One", Item = "Item Two"}, new ObjectOne {Name = "Name Two", Item = "Item Three"} }; var twoList= oneList.GroupBy(x => x.Name) .Select (x => new ObjectTwo { Name = x.Key, Items = x.Select(t => t.Item) }); 
+8
source

This can be done using the group by LINQ statement:

 var obj2List = from o in list group o by o.Name into g select new ObjectTwo() {Name = g.Key, Items = g.Select(x => x.Item)}; 
+2
source

All Articles