我一直在尝试将下面的foreach语句转换为LINQ语句,但似乎无法绕过它。欢迎任何帮助。
IDictionary<string, IDictionary<string, ICollection<string>>> Highlights { get; set; }
foreach (var r in matchingProducts.Highlights)
{
string szKey = r.Key;
var ar = r.Value.ToArray();
foreach (var s in ar)
{
string szCat = s.Key;
var sr = s.Value.ToArray();
foreach (var t in sr)
{
string szName = t;
//todo: update the corresponding matchingProduct records
// using the return values from szKey, szCat, szName
}
}
}
matchingProducts
public class Product {
[SolrUniqueKey("id")]
public string Id { get; set; }
[SolrField("sku")]
public string SKU { get; set; }
[SolrField("name")]
public string Name { get; set; }
[SolrField("manu_exact")]
public string Manufacturer { get; set; }
[SolrField("cat")]
public ICollection<string> Categories { get; set; }
[SolrField("features")]
public ICollection<string> Features { get; set; }
[SolrField("price")]
public decimal Price { get; set; }
[SolrField("popularity")]
public int Popularity { get; set; }
[SolrField("inStock")]
public bool InStock { get; set; }
[SolrField("timestamp")]
public DateTime Timestamp { get; set; }
[SolrField("weight")]
public double? Weight { get; set;}
}
答案 0 :(得分:1)
您可以通过编写
将字典展平为最里面集合中的项目dict.Values.SelectMany(d => d.Values).SelectMany(c => c)
在这些lambda表达式中,d
是内部字典,c
是最里面的ICollection
。
你可以得到这样的外键:
dict.SelectMany(kvpOuter =>
kvpOuter.Value.SelectMany(kvpInner =>
kvpInner.Value.Select(item =>
new {
OuterKey = kvpOuter.Key,
InnerKey = kvpInner.Key,
Item = item,
}
)
)
)
答案 1 :(得分:1)
您可以枚举以下LINQ查询
var query = from r in Highlights
let szKey = r.Key
let szValue = r.Value
from s in szValue
let szCat = s.Key
let sr = s.Value
from t in sr
let szText = t
select new { Key = szKey, Category = szCat, Text = szText };
// or, also, you can use this small query
var query = from r in Highlights
from s in r.Value
from t in s.Value
select new {Key = r.Key, Category = s.Key, Text = t};
foreach(var element in query)
{
ProcessUpdate(element.Key, element.Category, element.Text);
}