110

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.

1
  • 1
    The Name property in the SampleClass class should be of type string right?
    – sonyisda1
    Commented May 13, 2020 at 18:53

5 Answers 5

148

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

4
  • 1
    Does this return all of the objects that match nameToExtract?
    – IAbstract
    Commented Jan 10, 2011 at 20:43
  • 4
    Specifically, all the objects whose Name property matches nameToExtract, yes.
    – Dan J
    Commented Jan 10, 2011 at 20:45
  • 8
    thx - is there a boolean version whcih simply returns true or false if it does or doesn't exist?
    – BenKoshy
    Commented Mar 3, 2017 at 3:23
  • 21
    @BKSpurgeon Yes, that's the Any() method.
    – Dan J
    Commented Mar 3, 2017 at 23:26
26
list.Any(x=>x.name==string)

Could check any name prop included by list.

2
  • 1
    This is the best solution for this question. Also because it's much better to read. Commented Jan 5, 2023 at 8:10
  • I think this answer may have missed the requirements of the question: the OP is asking how to produce a new list that contains only those elements of the original list whose Name property matches a value. The .Any() method does not do that.
    – Dan J
    Commented Mar 4, 2023 at 0:44
13
myList.Where(item=>item.Name == nameToExtract)
0
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);
3
using System.Linq;    
list.Where(x=> x.Name == nameToExtract);

Edit: misread question (now all matches)

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.