通过Linq查询从双值的元组返回一个List

Naj*_*eeb -3 c# linq collections tuples list

我有一个具有双值的元组列表:

List<Tuple<string, string>> Descriptions;
Run Code Online (Sandbox Code Playgroud)

我一直在为此添加内容,如下所示:

Descriptions.Add (new Tuple<string, string> ("max", "some description"));
Descriptions.Add (new Tuple<string, string> ("joe", "some description"));
Descriptions.Add (new Tuple<string, string> ("jane", "some description"));
Descriptions.Add (new Tuple<string, string> ("max", "some other description"));
Run Code Online (Sandbox Code Playgroud)

我想使用Linq检索一个列表,其中Item1元组是一个特定的值,比如说"max".我可以使用这段代码:

var s = Descriptions.Where (x => x.Item1 == "max");
Run Code Online (Sandbox Code Playgroud)

但是这将分配小号元组,这是我不希望的列表.我只想要一个描述字符串的列表,也就是说,它应该返回一个list<string>包含与Item1字符串相关的所有描述"max".

Zoh*_*led 5

用途Select:

var s = Descriptions.Where (x => x.Item1 == "max").Select(y => y.Item2);
Run Code Online (Sandbox Code Playgroud)

这将返回一个IEnumerable<string>.如果你想要一个列表,你还需要ToList在最后添加:

var s = Descriptions.Where (x => x.Item1 == "max").Select(y => y.Item2).ToList();
Run Code Online (Sandbox Code Playgroud)

或者您可以使用查询语法:

var s = from d in Descriptions
        where d.Item1 == "max"
        select d.Item2;
Run Code Online (Sandbox Code Playgroud)

这与第一个选项相同.实际上,编译器会将查询语法转换为linq的扩展方法.