【LINQ笔记】AsParallel()、SelectMany()、SequenceEqual()、Zip()

AsParallel()

并行化操作,大集合使用,提高速度

personList.AsParallel().Sum(p => p.CompanyID);

SelectMany()

合并集合的集合成员

Dictionary<int, List<string>> dict = new Dictionary<int, List<string>>();
IEnumerable<string> values = dict.SelectMany(d => d.Value); 
var list2 = teachers.SelectMany(teacher => teacher.Students);

复杂案例:

var variants = new Dictionary<string, List<string>>
        {
            { "Color", new List<string> { "Red", "Green" } },
            { "Size", new List<string> { "S", "M" } },
            { "Style", new List<string> { "A" } }
        };
var list = new List<string[]>{
 new string[]{"Red","Green"},
 new string[]{"S","M"},
 new string[]{"A"}
};

var results1 = Combine2(list);
var results2 = Combine(variants);

static List<string> Combine(Dictionary<string, List<string>> dict)
{
    List<string> results = new List<string> { "" };
    foreach (var item in dict)
    {
        results = results.SelectMany(x => item.Value, (x, y) => $"{x}_{y}").ToList();
    }
    return results;
}
static List<string> Combine2(List<string[]> list)
{
    List<string> results = new List<string> { "" };
    foreach (var item in list)
    {
        results = results.SelectMany(x => item, (x, y) => $"{x}_{y}").ToList();
    }
    return results;
}

输出:

_Red_S_A
_Red_M_A
_Green_S_A
_Green_M_A

SequenceEqual()

逐一比较两个集合中的元素,如果相同就返回true,元素位置不同也不行

List<int> intList1 = new List<int>() { 1, 2, 3 };
List<int> intList2 = new List<int>() { 2,1,3};            
Console.WriteLine(intList1.SequenceEqual(intList2));//false

Zip()

将指定函数应用于两个序列的对应元素,以生成结果序列

 IEnumerable<int> result = intList1.Zip(intList2, (i, j) => {
                return i + j;
            });

AsQueryable()

将Lambda表达式作为数据存储起来,Expression表达式

posted @ 2019-12-29 12:13  .Neterr  阅读(651)  评论(0)    收藏  举报