加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 02:01:55 所属栏目:百科 来源:网络整理
导读:我很难理解为什么我会得到我的结果. 我有两个字符串列表: var list1 = new ListString {"item 1","item 2"};var list2 = new ListString { "item 3","item 4" }; 版本1 – 输出:“第2项” var item = from x in (list1.Concat(list2)) where x.EndsWith("2
我很难理解为什么我会得到我的结果.

我有两个字符串列表:

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输出“第2项”.为什么会出现这种情况?

解决方法

在版本3中,选择x将返回与您的critera匹配的字符串序列;它恰好是一个包含一个项目的序列.

无论你传入什么内容,Console.WriteLine都会在内部调用.ToString().由于IEnumerable< T>没有有意义的字符串表示形式,因此.NET中的默认值是打印该类型的字符串名称.

根据你的措辞,我认为你的混淆部分来自于误解为什么版本2的工作方式.在版本2中,选择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.”

所以事实上,版本2中的项目是IEnumerable< char>有一个元素.在IEnumerable< char>上调用Console.WriteLine()将按顺序打印字符.所以你得到“我”.

(注意:在我回答之后,我看到问题被编辑为在投影内部和结果上调用.First(),因此关于将IEnumerable< char>传递给Console.WriteLine的位不再完全相关)

请记住,LINQ几乎是关于使用集合,直到您明确减少它们为止.例如,Select只是一个投影或转换.它返回传递给它的相同数量的项目,进行转换.减少集合的地方,但它仍然是一套.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读