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.
You can use the Enumerable. Where extension method: var matches = myList. Where(p => p.Name == nameToExtract);
List<T>. Contains(T) Method is used to check whether an element is in the List<T> or not.
Exists() function in C#. The Array. Exists() function returns a boolean value that is true if the element exists in the array and false if it does not exist in the array.
To check if an element is present in the list, use List. Contains() method.
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
myList.Where(item=>item.Name == nameToExtract)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With