繁体   English   中英

加速LINQ对象查询

[英]Speed up LINQ Object Query

我试图加快以下LINQ对象查询的速度:

var setOfCodes = codeList1
    .SelectMany(q => q.Codes)
    .Union(codeList2.SelectMany(q => q.Codes)
    .Union(codeList3.SelectMany(q => q.Codes)
    .ToList();

哪里

codeListX is a List<Item>

public Item {
    public List<int> Codes = new List<int>();
}

例:

var codeList1 = new List<Item> {
    new Item {
        Codes = new List<int> {
            100,
            105,
            110
        }
    },
    new Item {
        Codes = new List<int> {
            100,
            110,
            115
        }
    },
};
var codeList2 = new List<Item> {
    new Item {
        Codes = new List<int> {
            150,
            155,
            160
        }
    },
    new Item {
        Codes = new List<int> {
            150,
            155,
            170
        }
    },
};

输出应该是(不要为命令烦恼,我可以稍后排序):

100, 105, 110, 115, 150, 155, 160, 170

IE:输出一个列表,其中包含出现在codeListX内的所有代码。

有更快的方法吗?

您可以这样写:

var setOfCodes = new[] { codeList1, codeList2, codeList3 }
    .SelectMany(x => x)
    .SelectMany(x => x.Codes)
    .Distinct()
    .ToList();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM