gpt4 book ai didi

c# - Linq 查询从多个 List 中选择单个字符串

转载 作者:太空狗 更新时间:2023-10-30 00:40:56 27 4
gpt4 key购买 nike

我很难理解为什么我会得到现在的结果。

我有两个字符串列表:

var list1 = new List<String> {"item 1", "item 2"};
var list2 = new List<String> { "item 3", "item 4" };

版本 1 - 输出:“项目 2”

var item =
from x in (list1.Concat(list2))
where x.EndsWith("2")
select x;

Console.WriteLine(item.First());

版本 2 - 输出:“i”

var item =
from x in (list1.Concat(list2))
where x.EndsWith("2")
select x.First();

Console.WriteLine(item.First());

版本 3 - 输出:“System.Linq.Enumerable+WhereEnumerableIterator`1[System.String]”

var item =
from x in (list1.Concat(list2))
where x.EndsWith("2")
select x;

Console.WriteLine(item);

鉴于版本 2 输出“i”,我希望版本 3 输出“item 2”。为什么会出现这种行为?

最佳答案

在版本 3 中,select x正在返回符合您的标准的字符串序列;它恰好是一个包含其中一项的序列。

Console.WriteLine内部调用 .ToString()无论你传递给它什么。由于 IEnumerable<T> 没有有意义的字符串表示形式, .NET 中默认打印类型的字符串名称。

根据您的措辞,我认为您的部分困惑确实来自对版本 2 为何如此工作的误解。在版本 2 中,select x.First()实际上有点奇怪/巧合,因为一个字符串也是一个IEnumerable<char> ,因此您可以对字符串执行 LINQ 操作。 .First()返回 char 的第一个元素序列,对于符合您的条件的每个结果。所以你是说:

"For each element which matches my criteria, select the first character, and then return the sequence of all the first characters for the matches."

所以实际上,item在版本 2 中是一个 IEnumerable<char>里面有一个元素。打电话Console.WriteLine()IEnumerable<char> 上只会按顺序打印字符。所以你得到“我”。

(注意:我看到在我回答这个问题后,问题被编辑为在投影和结果中调用 .First(),所以关于将 IEnumerable<char> 传递给 Console.WriteLine 的部分不再完全相关)

请记住,LINQ 几乎与处理集合有关,直到您明确地减少它们。例如,Select只是一个投影或转换。它返回传递给它的相同数量的项目,经过转换。 Where减少集合,但它仍然是集合。

关于c# - Linq 查询从多个 List<string> 中选择单个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23834756/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com