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

C#.NetList

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

myList.Where(item=>item.Name == nameToExtract)

Solution 3 - C#

Further to the other answers suggesting LINQ, another alternative in this case would be to use the FindAll instance method:

List<SampleClass> results = myList.FindAll(x => x.Name == nameToExtract);

Solution 4 - C#

list.Any(x=>x.name==string)

Could check any name prop included by list.

Solution 5 - C#

using System.Linq;    
list.Where(x=> x.Name == nameToExtract);

Edit: misread question (now all matches)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionryblView Question on Stackoverflow
Solution 1 - C#Dan JView Answer on Stackoverflow
Solution 2 - C#George PolevoyView Answer on Stackoverflow
Solution 3 - C#LukeHView Answer on Stackoverflow
Solution 4 - C#AkayeView Answer on Stackoverflow
Solution 5 - C#JanWView Answer on Stackoverflow