循环虽然集合在其他集合和LINQ lambda表达式中

时间:2015-06-08 23:16:49

标签: c# linq lambda

这里我从所有FactoryOption中选择带有“TRANSMISSION”标题的描述

tOptions = _vDetails.fOptions
                    .Where(x => (x.header != null && x.header.Value.ToUpper() == "TRANSMISSION"))
                    .Select(x => x.description)
                    .SelectMany(x => x);

如果标题为null我想在不明确的选项中搜索与“TRANSMISSION”相匹配的标题

如下所示:

foreach (var fOptions in _vDetails.fOptions)
{
    if (fOptions.header != null && fOptions.header.Value.ToUpper() == "TRANSMISSION")
    {
        tOptions = fOptions.description;
    }
    else if (fOptions.ambiguousOption != null)
    {
        foreach (var ambiguousOption in fOptions.ambiguousOption)
        {
            if (ambiguousOption.header != null && ambiguousOption.header.Value.ToUpper() == "TRANSMISSION")
            {
                newseq = tOptions.Concat(ambiguousOption.description);
            }
        }
    }
}

我正在尝试更改现有的LINQ lambda表达式以迭代fOptions.ambiguousOption,有人可以建议。

2 个答案:

答案 0 :(得分:2)

如果我理解正确,我认为你只想做这样的事情:

var result = options.SelectMany(o => IsTransmissionHeader(o.header) ? o.description :
                                         o.ambigousOptions == null || !o.ambigousOptions.Any(x => IsTransmissionHeader(x.header)) ? new string[] { } : 
                                         o.ambigousOptions.First(x => IsTransmissionHeader(x.header)).description)
                    .Where(d => d.Any());

我添加了一个静态方法来检查标题:

public static bool IsTransmissionHeader(Header header)
{
    return header != null && header.Value != null && header.Value.ToUpper() == "TRANSMISSION"
}

这将返回IEnumerable<string>。如果您希望IEnumerable<IEnumerable<string>>SelectMany更改为Select

修改

要从ambigousOptions获取所有传输描述值,您需要更改最后一行,使其如下所示:

var result = options.SelectMany(o => IsTransmissionHeader(o.header) ? o.description :
                                         o.ambigousOptions == null || !o.ambigousOptions.Any(x => IsTransmissionHeader(x.header)) ? new string[] { } :
                                         o.ambigousOptions.Where(x => IsTransmissionHeader(x.header)).SelectMany(x => x.description));

答案 1 :(得分:0)

这应该做你想要的。在这里,我将FactoryOption中具有匹配标题的描述与AmbiguousOption中具有匹配标题的描述相结合。

var descriptions = details.SelectMany(d => d.FactoryOptions.Where(f => f.Header == "TRANSMISSION").Select(f => f.Description)
    .Concat(d.FactoryOptions.SelectMany(f => f.AmbiguousOptions.Where(a => a.Header == "TRANSMISSION").Select(a => a.Description))));

<强>更新 上面的答案适用于从Detail集合开始的情况。如果您从单个Detail开始,那么您可以执行以下操作:

_vehicleDetails.FactoryOptions.Where(f => f.Header == "TRANSMISSION").Select(f => f.Description)
    .Concat(_vehicleDetails.FactoryOptions.SelectMany(f => f.AmbiguousOptions.Where(a => a.Header == "TRANSMISSION").Select(a => a.Description)));