Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a list of objects contains a property with a specific value

Tags:

c#

.net

list

Say I have the following code:

class SampleClass {     public int Id {get; set;}     public string Name {get; set;} } List<SampleClass> myList = new List<SampleClass>(); //list is filled with objects ... string nameToExtract = "test"; 

So my question is what List function can I use to extract from myList only the objects that have a Name property that matches my nameToExtract string.

I apologize in advance if this question is really simple/obvious.

like image 817
rybl Avatar asked Jan 10 '11 20:01

rybl


People also ask

How do you check if a list of object contains a value?

You can use the Enumerable. Where extension method: var matches = myList. Where(p => p.Name == nameToExtract);

How do you check whether a list contains a specified element?

List<T>. Contains(T) Method is used to check whether an element is in the List<T> or not.

How do you check if an array of objects contains a value in C#?

Exists() function in C#. The Array. Exists() function returns a boolean value that is true if the element exists in the array and false if it does not exist in the array.

How do you check if a list contains an object c#?

To check if an element is present in the list, use List. Contains() method.


2 Answers

You can use the Enumerable.Where extension method:

var matches = myList.Where(p => p.Name == nameToExtract); 

Returns an IEnumerable<SampleClass>. Assuming you want a filtered List, simply call .ToList() on the above.


By the way, if I were writing the code above today, I'd do the equality check differently, given the complexities of Unicode string handling:

var matches = myList.Where(p => String.Equals(p.Name, nameToExtract, StringComparison.CurrentCulture)); 

See also

like image 183
Dan J Avatar answered Oct 13 '22 23:10

Dan J


myList.Where(item=>item.Name == nameToExtract) 
like image 33
George Polevoy Avatar answered Oct 13 '22 23:10

George Polevoy