C# Linq操作List或数组

Linq对数组操作分为合并、交集、差集等。

List numbers1 = new List() { 1, 3, 5 };
List numbers2 = new List() { 3,5,11, 13, 15 };

//合并排序
var newList = numbers1.Concat(numbers2).OrderBy(n => n);
foreach (var item in newList)
{
    Console.WriteLine(item);
}

//合并数组,并去除重复,排序
var newList = numbers1.Concat(from n in numbers2 where !numbers1.Contains(n) select n).OrderBy(n => n);
foreach (var item in newList)
{
    Console.WriteLine(item);
}

//合并,去重,排序
var newList = numbers1.Union(numbers2).OrderBy(n => n);
foreach (var item in newList)
{
    Console.WriteLine(item);
}

//取两个数组交集,排序
var newList = numbers1.Intersect(numbers2).OrderBy(n => n);
foreach (var item in newList)
{
    Console.WriteLine(item);
}

//取出数组1与数组2的差集,排序
var newList = numbers1.Except(numbers2).OrderBy(n => n);
foreach (var item in newList)
{
    Console.WriteLine(item);
}

//判断两个数组是否有交集
var exists = numbers1.Exists(delegate(int n)
{
    return numbers2.Exists(delegate(int i)
    {
        if (n == i)
            return true;
        else return false;
    });
});
Console.WriteLine(exists); 


你可能感兴趣的:(C# Linq操作List或数组)