在List<>中查找元素包含一个值 [英] Find element in List<> that contains a value

查看:76
本文介绍了在List<>中查找元素包含一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个List<MyClass> MyList其中

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?

推荐答案

都可以使用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.)

或使用 Find 代替FindIndex:

var value = MyList.Find(item => item.name == "foo").value;

尽管如此,我还是强烈建议使用LINQ-如今这是一种更加惯用的方法.

I'd strongly suggest using LINQ though - it's a much more idiomatic approach these days.

(我还建议遵循.NET命名约定.)

(I'd also suggest following the .NET naming conventions.)

这篇关于在List&lt;&gt;中查找元素包含一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆