Reputation: 10638
Initially I have a list of items:
List<Item> mySourceList;
which Item is:
Item Class:
public class Item
{
public DateTime Date
{
get;
set;
}
public string ProviderID
{
get;
set;
}
public List<AnotherClass> listOfitems
{
get;
set;
}
public byte[] Img
{
get;
set;
}
// Other properties
public long GroupID
{
get;
set;
}
}
I need to group mySourceList by ProviderID and Date so I do below:
var grp = mySourceList .GroupBy(e => new { e.ProviderID, e.Date });
Then I perform some opertions in this grouped list:
int groupId = 1;
foreach (var group in grp)
{
int id = group.Count() > 1 ? groupId++ : 0;
// Loop through each item within group
foreach (var item in group)
item.GroupID = id;
}
And Finally, I am trying to convert mySourceList list into a new one, this new one must be List again, so I am trying below but it is not working:
List<Item> myDestList = grp.ToList<Item>();
How can I convert to List ?
I am using Visual Studio 2008 and NET Framework 3.5 SP1
Upvotes: 1
Views: 873
Reputation: 10638
I have done below by taking advantage of the operation to update grouped list in the loops:
List<Item> groupedList = new List<Item>();
int groupId = 1;
foreach (var group in grp)
{
int id = group.Count() > 1 ? groupId++ : 0;
// Loop through each item within group
foreach (var item in group)
{
item.GroupID = id;
groupedList.add(Item);
}
}
myDestList = groupedList;
Fabio solution also works.
Upvotes: 0
Reputation: 32445
Use SelectMany
extension method.
grp
is of type IEnumerable<IGrouping<'a, Item>>
- so it some kind of list of list.
And you need return flattened list of all items.
List<Item> myDestList = grp.SelectMany(g => g).ToList();
Another approach is using your original list, because your code updating already existed items.
Upvotes: 4