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?
hi body very late but i am writing
if(mylist.contains(value)){}
Enumerable.First
returns the element instead of an index. In both cases you will get an exception if no matching element appears in the list (your original code will throw an IndexOutOfBoundsException
when you try to get the item at index -1, but First
will throw an InvalidOperationException
).
MyList.First(item => string.Equals("foo", item.name)).value
You can use the Where
to filter and Select
to get the desired value.
MyList.Where(i=>i.name == yourName).Select(j=>j.value);
I would use .Equals()
for comparison instead of ==
.
Like so:
MyClass item = MyList.Find(item => item.name.Equals("foo"));
Particularly because it gives you options like StringComparison, which is awesome. Example:
MyClass item = MyList.Find(item => item.name.Equals("foo", StringComparison.InvariantCultureIgnoreCase);
This enables your code to ignore special characters, upper and lower case. There are more options.
Using function Find is cleaner way.
MyClass item = MyList.Find(item => item.name == "foo");
if (item != null) // check item isn't null
{
....
}
Source: Stackoverflow.com