1

I have a list of objet having "ean" and "eanAlt" properties.

This works:

List<string> eanList = new List<string>();
eanList.AddRange(toGroup.Where(a => a.ean.Length > 0).Select(b => b.ean).ToArray());
eanList.AddRange(toGroup.Where(a => a.eanAlt.Length > 0).Select(b => b.eanAlt).ToArray());

But how can I do it in one query? (I suppose with SelectMany, but can't find how)

4

2 回答 2

4

要使用SelectMany,您需要先转换eaneanAlt列出:

  eanList = toGroup
       .SelectMany(a => new List<string> { a.ean, a.alt })
       .Where(s => !string.IsNullOrEmpty(s))
       .ToList();  
于 2013-04-23T01:14:10.493 回答
3

您的代码可以ean同时eanAlt选择toGroup. 我认为要获得完全相同的行为,您必须执行以下操作:

eanList.AddRange(
    from a in toGroup
    from b in new[] { a.ean, a.eanAlt }
    where b.Length > 0
    select b);

ToArray这里不需要注释。

或者,如果您更喜欢流利的语法,您可以这样做(尽管我认为这会使发生的事情变得不太清楚):

eanList.AddRange(toGroup.SelectMany(a => new[] { a.ean, a.eanAlt }).Where(b => b.Length > 0));
于 2013-04-23T01:13:30.460 回答