Reputation: 14100
Goal:
Retrieve the variable ff as a datatype List<Part>
after executing the code
parts.GroupBy(b => new { b.PartName, b.PartId }).ToList();
The result should be three unique Part
Problem:
I tried a find solution but in the end it always end as the following code.
List<Part> parts = new List<Part>();
// Add parts to the list.
parts.Add(new Part() { PartName = "crank arm", PartId = 1234 });
parts.Add(new Part() { PartName = "crank arm", PartId = 1234 });
parts.Add(new Part() { PartName = "chain ring", PartId = 1334 });
parts.Add(new Part() { PartName = "regularseat", PartId = 1434 });
var ff = parts.GroupBy(b => new { b.PartName, b.PartId }).ToList();
Thank you!
Upvotes: 0
Views: 56
Reputation: 8676
You are missing Select
statement:
List<Part> ff = parts
.GroupBy(b => new { b.PartName, b.PartId })
.Select(g => new Part
{
PartName = g.Key.PartName
PartId = g.Key.PartId
})
.ToList();
If your goal is just select distinc Part
objects, then the GroupBy
may be slower than Distinct
(see this answer). But you have to test and see yourself.
If you want to use Distinct
then you have to create equality comparer by implementing IEqualityComparer interface. Be sure to check JonSkeet's answer for good GetHashCode
method in case you choosed Distinct
.
Upvotes: 1
Reputation: 141
You can select the first element from each group with Select. Then you have a flat list of Parts.
List<Part> parts = new List<Part>();
// Add parts to the list.
parts.Add(new Part() { PartName = "crank arm", PartId = 1234 });
parts.Add(new Part() { PartName = "crank arm", PartId = 1234 });
parts.Add(new Part() { PartName = "chain ring", PartId = 1334 });
parts.Add(new Part() { PartName = "regularseat", PartId = 1434 });
var ff = parts.GroupBy(b => new { b.PartName, b.PartId }).Select(group => group.First()).ToList();
Upvotes: 1