Lambda表达式有两个对象

时间:2011-02-01 16:29:38

标签: c# lambda

我知道这可以使用lambda表达式重写。但我似乎无法弄明白。有没有人对如何用lambda写出来有意见。

            foreach (var _systemItem in _systemData)
            {
                foreach (var _institutionItem in _institutionData)
                {
                    if (_systemItem.LookupValue == _institutionItem.OriginalSystemLookupValue)
                    {
                        _values.Add(new LookupValue()
                        {
                            DisplayText = _institutionItem.LookupText,
                            Value = _institutionItem.LookupValue
                        });
                    }
                    else
                    {
                        _values.Add(new LookupValue()
                        {
                            DisplayText = _systemItem.LookupText,
                            Value = _systemItem.LookupValue
                        });
                    }
                }
            }

3 个答案:

答案 0 :(得分:4)

像这样:

values.AddRange(from s in _systemData
                from i in institutionData
                select s.LookupValue == i.OriginalSystemLookupValue ?
                    new LookupValue {
                        DisplayText = _institutionItem.LookupText,
                        Value = _institutionItem.LookupValue
                    }
                :   new LookupValue {
                        DisplayText = _systemItem.LookupText,
                        Value = _systemItem.LookupValue
                    }
               );

答案 1 :(得分:3)

_values一个List<LookupValue>是空的吗?如果是这样,那看起来可能是这样的:

_values = (from x in _systemData
           from y in _institutionData
           let item = x.LookupValue == y.OriginalSystemLookupValue ? x : y
           select new LookupValue { DisplayText = item.LookupText,
                                    Value = item.LookupValue })
          .ToList();

假设_systemItem_institutionItem属于同一类型。如果它们是不相关的类型,您可能希望为它们提供一个定义LookupTextLookupValue(或甚至是ToLookupValue方法)的公共接口,然后在条件中强制转换其中一个操作数操作员到界面。例如:

_values = (from x in _systemData
           from y in _institutionData
           let item = x.LookupValue == y.OriginalSystemLookupValue
                      ? (ILookupSource) x : y
           select item.ToLookupValue())
          .ToList();

答案 2 :(得分:0)

当然,我有意见。我会这样写:

var pairs = _systemData.SelectMany(s =>
    _institutionData.Select(i => new { System = s, Institution = i }));

_values.AddRange(pairs.Select(x =>
{
    bool match = x.System.LookupValue == x.Insitution.OriginalSystemLookupValue;

    return match ? new LookupValue(x.Institution) : new LookupValue(x.System);
}));

LookupValue的对象初始值设定项移动到采用InstitutionSystem的实际构造函数中。