I have a List<MyClass> MyList
where
public class MyClass { public string name { get; set; } public string value { get; set; } }
Given a name, I'd like to get the corresponding value. I have it currently implemented as:
MyList[MyList.FindIndex(item => String.Compare(item.name, "foo", 0) == 0)].value
Is there a cleaner way to do this?
List<T>. Contains(T) Method is used to check whether an element is in the List<T> or not.
if (myList. Contains(myString)) string element = myList. ElementAt(myList. IndexOf(myString));
You could use a nested Any() for this check which is available on any Enumerable : bool hasMatch = myStrings. Any(x => parameters. Any(y => y.
Select(x => new { x, count = x. tags. Count(tag => list. Contains(tag)) }) .
Either use LINQ:
var value = MyList.First(item => item.name == "foo").value;
(This will just find the first match, of course. There are lots of options around this.)
Or use Find
instead of FindIndex
:
var value = MyList.Find(item => item.name == "foo").value;
I'd strongly suggest using LINQ though - it's a much more idiomatic approach these days.
(I'd also suggest following the .NET naming conventions.)
You can use the Where
to filter and Select
to get the desired value.
MyList.Where(i=>i.name == yourName).Select(j=>j.value);
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