Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
127 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...