你可以将多个列表与LINQ结合使用吗?
说我有两个清单:
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}));
preetsangha的答案是完全正确的,但如果你不想要一个查询表达式那么它是:
var result = list1.SelectMany(l1 => list2, (l1, l2) => new { i = l1, s = l2} );
(这就是编译器将查询表达式编译成的内容 – 它们是相同的。)
var result = from l1 in list1 from l2 in list2 select new { i = l1, s = l2};
- DriveInfo.GetDrives()在以管理员身份运行时不返回映射驱动器
- 使用c#将文件(从流)保存到磁盘
- 查询正文必须以select子句或group子句结束,为什么这里出现错误?
- 在WCF服务应用程序中找不到类型或命名空间名称“var”
- AutomationElement使用Inspect.exe显示,但在使用UIAutomationCore.dll或System.Windows.Automation时不显示
- 没有数据源控制的高效Gridview分页问题
- CultureInfo.CurrentCulture在String.Format()中是否真的必要?
- 创建单实例WPF应用程序的正确方法是什么?
- 多核处理器上的多个线程