0

次のコードがあり、linq に変換したいと考えています。外部 foreach 内の 2 つの 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

ノガードへの私のコメントに基づいて構築するには、次のようにします。

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 に答える