91

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.

rybl
  • 1,439
  • 2
  • 13
  • 22

5 Answers5

132

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

Dan J
  • 15,852
  • 6
  • 49
  • 79
  • 1
    Does this return all of the objects that match `nameToExtract`? – IAbstract Jan 10 '11 at 20:43
  • 4
    Specifically, all the objects whose `Name` property matches `nameToExtract`, yes. – Dan J Jan 10 '11 at 20:45
  • 7
    thx - is there a boolean version whcih simply returns true or false if it does or doesn't exist? – BenKoshy Mar 03 '17 at 03:23
  • 18
    @BKSpurgeon Yes, that's the [Any()](https://docs.microsoft.com/en-us/dotnet/core/api/system.linq.enumerable#System_Linq_Enumerable_Any__1_System_Collections_Generic_IEnumerable___0__System_Func___0_System_Boolean__) method. – Dan J Mar 03 '17 at 23:26
12
myList.Where(item=>item.Name == nameToExtract)
George Polevoy
  • 7,122
  • 3
  • 33
  • 59
5

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);
LukeH
  • 252,910
  • 55
  • 358
  • 405
4
list.Any(x=>x.name==string)

Could check any name prop included by list.

Akaye
  • 41
  • 1
3
using System.Linq;    
list.Where(x=> x.Name == nameToExtract);

Edit: misread question (now all matches)

JanW
  • 1,729
  • 13
  • 23