Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find first occurrence with LINQ

Tags:

c#

.net

linq

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?

like image 250
4thSpace Avatar asked Dec 05 '11 23:12

4thSpace


People also ask

How do I get my first record in Linq?

In order to select the first record from a list of entities with LINQ, we use the First or the FirstOrDefault methods.

Which function is used to get first record in Linq collection?

LINQ Syntax - Fluent vs. The . First() method does just what you think it does – it gets the first element in the list.

What is first in Linq?

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.


2 Answers

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());
like image 66
Reed Copsey Avatar answered Nov 01 '22 18:11

Reed Copsey


At the end of statement add ".FirstOrDefault()"

like image 2
Marcin Wieczorek Avatar answered Nov 01 '22 18:11

Marcin Wieczorek