0

我有以下代码,想把它翻译成 linq。考虑到外部 foreach 中的两个 foreach 循环,是否有可能?目前我只能将内部 foreach 循环转换为 linq,但代码仍然很长,我认为它可能会更短。

List<complexType> listOfComplex = ...some list...
List<complexType> newListOfCOmplex = new List<complexType>();
SomeObjectType someObject = ...some object...

foreach(var cT in listOfComplex)
{
    var someObjectPropertyValue = someObject.property.FirstOrDefault(a=>a.value == smth);

    if(someObjectPropertyValue == null)
    {
        return null;
    }
    var t = someObjectPropertyValue.Something.AnotherSomethin;

    if(t==null)
    {
        newListOfCOmplex.Add(cT);
        continue;
    }

    var collectionFirst = t.Where(s=>s.value == firstValue);

    foreach (var f in collectionFirst)
    {
        someOtherMethod(f);
    }
    newListOfCOmplex.Add(cT);

    var collectionSecond = t.Where(s=>s.value == secondValue);

    foreach (var s in collectionSecond)
    {
        someOtherMethod(s);
    }

}
4

2 回答 2

2

整个代码非常可疑,因为变量cT只添加到列表中,在 foreach 循环中都没有检查它的属性。

无论这是原始行为还是混淆的结果,您都应该修改您的样本。

至于当前样本处理循环的更好方法是

List<complexType> listOfComplex = ...some list...
//List<complexType> newListOfCOmplex = new List<complexType>();
SomeObjectType someObject = ...some object...

//Totaly unneccessary as newListOfCOmplex is complete copy of listOfComplex 
//foreach(var cT in listOfComplex)
//{
//  newListOfCOmplex.Add(cT);
//}    

var someObjectPropertyValue = someObject.property.FirstOrDefault(a=>a.value == smth) ?? return null;

var t = someObjectPropertyValue.Something.AnotherSomethin ?? return smth;

var collection = t.Where(s=>(s.value == firstValue || s.value == secondValue) ).ToList();
foreach (var f in collection) someOtherMethod(f);

return smth;
}
于 2012-11-20T17:17:02.630 回答
0

以我对 Nogard 的评论为基础,可以这样做:

newListOfComplex = listOfComplex.ToList();

var stream = someObject.property
                       .Where(a => a.value == smth)
                       .Select(a => a.Something.AnotherSomething)
                       .FirstOrDefault() ?? Enumerable.Empty<T>()
if(stream.Any())
{
    foreach( var f in stream.Where(s=> s.value == firstValue)
                            .Concat(stream.Where(s => s.value == secondValue)))
    someOtherMethod(f);
    return smth;
}
else return null;
于 2012-11-20T17:57:49.013 回答