当前位置:  开发笔记 > 编程语言 > 正文

你可以将多个列表与LINQ结合使用吗?

如何解决《你可以将多个列表与LINQ结合使用吗?》经验,为你挑选了2个好方法。

说我有两个清单:

var list1 = new int[] {1, 2, 3};
var list2 = new string[] {"a", "b", "c"};

是否可以编写一个LINQ语句来生成以下列表:

var result = new []{ 
    new {i = 1, s = "a"},
    new {i = 1, s = "b"},
    new {i = 1, s = "c"},
    new {i = 2, s = "a"},
    new {i = 2, s = "b"},
    new {i = 2, s = "c"},
    new {i = 3, s = "a"},
    new {i = 3, s = "b"},
    new {i = 3, s = "c"}
};

编辑:我忘了提到我在查询语法中不想要它.无论如何,根据preetsangha的回答,我得到了以下内容:

var result = list1.SelectMany(i =>  list2.Select(s => new {i = i, s = s}));

Preet Sangha.. 43

var result = from l1 in list1
             from l2 in list2       
             select new { i = l1, s = l2};


Jon Skeet.. 21

preetsangha的答案是完全正确的,但如果你不想要一个查询表达式那么它是:

var result = list1.SelectMany(l1 => list2, (l1, l2) => new { i = l1, s = l2} );

(这就是编译器将查询表达式编译成的内容 - 它们是相同的.)



1> Preet Sangha..:
var result = from l1 in list1
             from l2 in list2       
             select new { i = l1, s = l2};



2> Jon Skeet..:

preetsangha的答案是完全正确的,但如果你不想要一个查询表达式那么它是:

var result = list1.SelectMany(l1 => list2, (l1, l2) => new { i = l1, s = l2} );

(这就是编译器将查询表达式编译成的内容 - 它们是相同的.)

推荐阅读
php
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有