Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find element in List<> that contains a value

Tags:

c#

.net

list

linq

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?

like image 297
RaGe Avatar asked Apr 23 '13 19:04

RaGe


People also ask

How do you check whether a list contains a specified element?

List<T>. Contains(T) Method is used to check whether an element is in the List<T> or not.

How do you check whether a list contains a specific element in C#?

if (myList. Contains(myString)) string element = myList. ElementAt(myList. IndexOf(myString));

Can I check if a list contains any item from another list C#?

You could use a nested Any() for this check which is available on any Enumerable : bool hasMatch = myStrings. Any(x => parameters. Any(y => y.

How do you use LINQ to check if a list of strings contains any string in a list?

Select(x => new { x, count = x. tags. Count(tag => list. Contains(tag)) }) .


2 Answers

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.)

like image 160
Jon Skeet Avatar answered Oct 02 '22 22:10

Jon Skeet


You can use the Where to filter and Select to get the desired value.

MyList.Where(i=>i.name == yourName).Select(j=>j.value); 
like image 32
Hossein Narimani Rad Avatar answered Oct 02 '22 21:10

Hossein Narimani Rad