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.
5 Answers 5
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));
-
1Does this return all of the objects that match
nameToExtract
?IAbstract– IAbstract01/10/2011 20:43:33Commented Jan 10, 2011 at 20:43 -
4Specifically, all the objects whose
Name
property matchesnameToExtract
, yes.Dan J– Dan J01/10/2011 20:45:00Commented Jan 10, 2011 at 20:45 -
8thx - is there a boolean version whcih simply returns true or false if it does or doesn't exist?BenKoshy– BenKoshy03/03/2017 03:23:00Commented Mar 3, 2017 at 3:23
-
23
list.Any(x=>x.name==string)
Could check any name prop included by list.
-
1This is the best solution for this question. Also because it's much better to read.RuhrpottDev– RuhrpottDev01/05/2023 08:10:32Commented 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– Dan J03/04/2023 00:44:44Commented Mar 4, 2023 at 0:44
myList.Where(item=>item.Name == nameToExtract)
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);
using System.Linq;
list.Where(x=> x.Name == nameToExtract);
Edit: misread question (now all matches)
Name
property in theSampleClass
class should be of typestring
right?