Linq嵌套循环 [英] Linq for nested loop

查看:71
本文介绍了Linq嵌套循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的循环如下:

foreach(x in myColl) 
{
    foreach(var y in x.MyList) 
    {
        result.Add(x.MyKey + y)
    }
}

这意味着在我的内部循环中,我需要访问当前外部元素的属性.

That means within my inner loop I need access to a property of the current outer element.

我正在寻找LINQ语句,但不确定.我尝试使用

I´m looking for a LINQ-statement but I´m unsure on it. I tried it by using

result = myColl
    .SelectMany(x => x.MyList)
    .SelectMany(x => /* how to get the key of the outer loop here */ + x)

推荐答案

使用查询表达式很容易:

This is easy with query expressions:

(from x in myColl
 from y in x.MyList
 select x.MyKey + y).ToList()

这行得通,因为它可以翻译为:

This works because this translates to:

myColl
.SelectMany(x => x.MyList.Select(item => new { List = x, Item = item }))
.Select(x => ...) //rest of the query, whatever you like

关键是要保留列表以及列表项.使用匿名类型(或任何其他容器)将它们引导通过查询.

The key is to keep both the list as well as the list items. Channel them through the query using an anonymous type (or any other container).

这篇关于Linq嵌套循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆