LINQ系列:Linq to Object集合操作符

  集合操作符对元素的集合或序列集合进行操作,并返回一个集合。LINQ共有4种集合查询操作符:Distinct、Union、Intersect和Except。

1. Distinct

  Distinct操作符删除集合中重复的值,并返回该集合中互不相同的元素。

1>. 原型定义

public static IQueryable<TSource> Distinct<TSource>(this IQueryable<TSource> source);
public static IQueryable<TSource> Distinct<TSource>(this IQueryable<TSource> source, IEqualityComparer<TSource> comparer);

2>. 示例

int[] fibonacci = new int[] { 1, 1, 2, 3, 5, 8, 13, 21 };
var expr = from f in fibonacci
           select f;
expr.Distinct();
int[] fibonacci = new int[] { 1, 1, 2, 3, 5, 8, 13, 21 };
var expr = from f in fibonacci
           where f > 5
           select f;
expr.Distinct();
var expr = from p in context.Products
           select p.ProductName;
expr.Distinct();
var expr = context.Products
    .Select(p => p.ProductName)
    .Distinct();
int[] fibonacci = new int[] { 1, 1, 2, 3, 5, 8, 13, 21 };
var expr = fibonacci.Distinct().Count();
var expr = context.Products
    .Select(c => c.CategoryID)
    .Distinct()
    .Count();

 

int[] fibonacci = new int[] { 1, 1, 2, 3, 5, 8, 13, 21 };
var expr = fibonacci.Count(f => f % 2 == 0);

 

2. Union

  Union操作符返回两个序列或集合并集中的每个互不相同的元素。与Concat操作符不同,Union操作符返回互不相同的元素,而Concat操作符将返回所有的值。

1>. 原型定义

public static IEnumerable<TSource> Union<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second);
public static IEnumerable<TSource> Union<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource> comparer);

2>. 示例

int[] fibonacci = new int[] { 1, 1, 2, 3, 5, 8, 13, 21 };
int[] factorial = new int[] { 1, 2, 6, 24, 120 };

IEnumerable<int> expr = fibonacci.Union(factorial);

foreach (int item in expr)
{
    Console.Write(item + " ");
}
1 2 3 5 8 13 21 6 24 120

3. Intersect

  Intersect操作符返回两个序列的交集,即返回那些同时存在于两个序列或集合中的值。

1>. 原型定义

public static IEnumerable<TSource> Intersect<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second);
public static IEnumerable<TSource> Intersect<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource> comparer);

2>. 示例

int[] fibonacci = new int[] { 1, 1, 2, 3, 5, 8, 13, 21 };
int[] factorial = new int[] { 1, 2, 6, 24, 120 };

IEnumerable<int> expr = fibonacci.Intersect(factorial);

foreach (int item in expr)
{
    Console.Write(item + " ");
}
1 2

4. Except

  Except操作符与Intersect操作符相反,它返回两个序列中不同的部分,返回序列中所有不重复的值。

1>. 原型定义

public static IEnumerable<TSource> Except<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second);
public static IEnumerable<TSource> Except<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource> comparer);

2>. 示例

int[] fibonacci = new int[] { 1, 1, 2, 3, 5, 8, 13, 21 };
int[] factorial = new int[] { 1, 2, 6, 24, 120 };

IEnumerable<int> expr = fibonacci.Except(factorial);

foreach (int item in expr)
{
    Console.Write(item + " ");
}
3 5 8 13 21
posted @ 2014-10-22 13:47  libingql  阅读(952)  评论(0编辑  收藏  举报