简体   繁体   English

加速LINQ对象查询

[英]Speed up LINQ Object Query

I am attempting to speed up the following LINQ Object query: 我试图加快以下LINQ对象查询的速度:

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

Where 哪里

codeListX is a List<Item>

and

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

Example: 例:

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
        }
    },
};

And the output should be (Not fussed about order, I can sort later): 输出应该是(不要为命令烦恼,我可以稍后排序):

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

IE: Outputs a list containing all the codes that appear within the codeListX 's. IE:输出一个列表,其中包含出现在codeListX内的所有代码。

Is there a faster way to do this? 有更快的方法吗?

You can write it like this : 您可以这样写:

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