如何消除以下代码中的循环

时间:2018-09-06 19:17:40

标签: list linq loops

我想消除循环,以获得更好的编码和更高的性能。因此,在下面的代码中,我需要消除test1,test 2,test3的循环。

var test1 = _testP.cdata1(id, sdate)
                .Where(t => t.In != null).ToList();

var test2 = _testP.cdata2(id, sdate)
            .groupBy(p => p.In.id)
            .ToDictionary(p => p.Key, p => p.ToDictionary(q => q.Date, q => q));

var test3 = test1.Select(t =>
{
    Dictionary<Date, ClassB> cds = null;
    ClassB cd = null;

    if (test2.TryGetValue(t.In.Id, out cds)
        && cds.TryGetValue(t.date, out cd))
    {
        return new Tuple<ClassB, ClassA>(cd, t);
    }
    return null;
}).Where(p => p != null).ToList();


public IEnumerable<ClassA> cdata1(id, sdate)
{
    // do some operations
    return listA //(listA is the list of all the elements of ClassA object)
}

public IEnumerable<ClassB> cdata2(id, sdate)
{
    // do some operations
    return listA //(listA is the list of all the elements of ClassB object)            
}

public ClassA
{
    public testp in { get; }
    public Date date { get; }
    // other variables
}

public ClassB
{
    public testp in { get; }
    public Date date { get; }
    // other variables
}

请帮助我为上述代码段编写更好的代码。

0 个答案:

没有答案