106

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,609
  • 3
  • 14
  • 22

5 Answers5

147

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
  • 16,319
  • 7
  • 50
  • 82
  • 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
  • 8
    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
  • 21
    @BKSpurgeon Yes, that's the [Any()](https://learn.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
18
list.Any(x=>x.name==string)

Could check any name prop included by list.

Akaye
  • 189
  • 1
  • 3
  • This is the best solution for this question. Also because it's much better to read. – RuhrpottDev Jan 05 '23 at 08: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](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.any?view=net-7.0) does not do that. – Dan J Mar 04 '23 at 00:44
13
myList.Where(item=>item.Name == nameToExtract)
George Polevoy
  • 7,450
  • 3
  • 36
  • 61
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
  • 263,068
  • 57
  • 365
  • 409
3
using System.Linq;    
list.Where(x=> x.Name == nameToExtract);

Edit: misread question (now all matches)

JanW
  • 1,799
  • 13
  • 23