mPrivateClass2.Clear();
mClass2 .ForEach(p => mPrivateClass2.AddRange(p));
//The above is returning 13 not 2 as expected.
Why would you like it to return 2 elements only? Because you're using AddRange
, the entire grouping content is added into your List
, and because IGrouping<TKey, TElement>
implements IEnumerable<TElement>
will all elements classified to that group, you're getting 13. That's the expected and desired value for your code.
To get only 2 elements in mPrivateClass2
you'd have to decide, which element from the group should be added. For example, to add only the first item from each group use following:
mClass2.ForEach(p => mPrivateClass2.Add(p.First()));
You can add other methods, like OrderBy
, to sort the IGrouping
content before taking one item:
mClass2 .ForEach(p => mPrivateClass2.Add(p.OrderBy(x => Id).First()));