Using .NET LINQ, I'd like to find entries (Name) that start with PID equal to 0 or 1. But if the Name has both, I only want 0. In the following:
PID Name
0 P1
1 P1
1 P3
0 P4
0 P5
1 P5
I'll get back rows:
0 P1
1 P3
0 P4
0 P5
The PID values can go up to 10. Any suggestions how this can be done?
In order to select the first record from a list of entities with LINQ, we use the First or the FirstOrDefault methods.
LINQ Syntax - Fluent vs. The . First() method does just what you think it does – it gets the first element in the list.
Returns first element of a sequence, or a default value if no element is found. It throws an error Only if the source is null. you should use it, If more than one element is expected and you want only first element.
You can use:
var results = collection
.Where(item => item.PID == 0 || item.PID == 1)
.GroupBy(item => item.Name)
.Select(g => g.OrderBy(item => item.PID).First());
At the end of statement add ".FirstOrDefault()"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With