?Linq 的Set 操作....
共4个操作.Distinct、Union、Intersect、Except.
Distinct
下图演示 Enumerable.Distinct 方法对字符序列的行为。返回的序列包含输入序列的唯一元素。

Except
下图演示 Enumerable.Except 的行为。返回的序列只包含位于第一个输入序列但不位于第二个输入序列的元素。

Intersect
下图演示 Enumerable.Intersect 的行为。返回的序列包含两个输入序列共有的元素。

Union
下图演示对两个字符序列执行的联合操作。返回的序列包含两个输入序列的唯一的元素。

简单实例:
-
?#region?Set?Operator
-
????????
-
- ????????static?void?DistinctOperatorPrototype()
- ????????{
-
????????????string[]?presidents?=?{?"Adams",?"Arthur",?"Buchanan",?"Bush",?"Carter",?"Cleveland"?};
-
????????????Console.WriteLine("presidents?Count:"+presidents.Count());
-
????????????IEnumerable<string>?doublePresidents?=?presidents.Concat(presidents);
-
????????????Console.WriteLine("?after?Concat?presidents?Count:"?+?doublePresidents.Count());
-
????????????IEnumerable<string>?DistinctPresidents?=?doublePresidents.Distinct();
-
????????????Console.WriteLine("after?Distinct?presidents?Count:"?+?DistinctPresidents.Count());
- ????????}
-
????????
-
- ????????static?void?UnionPrototype()
- ????????{
-
????????????string[]?presidents?=?{?"Adams",?"Cleveland"?};
-
????????????Console.WriteLine("presidents?element?count:{0}",?presidents.Count());
-
????????????IEnumerable<string>?first?=?presidents.Take(4);
-
????????????IEnumerable<string>?second?=?presidents.Skip(2);
-
????????????Console.WriteLine("first?elements?count:{0}",?first.Count());
-
????????????Console.WriteLine("second?elements?count:{0}",?second.Count());
-
????????????IEnumerable<string>?concat?=?first.Concat(second);
-
????????????IEnumerable<string>?union?=?first.Union(second);
- ?????????
-
????????????Console.WriteLine("after?concat?element?count:{0}",?concat.Count());
-
????????????Console.WriteLine("after?union?element?count:{0}",?union.Count());
- ????????}
-
????????
-
- ????????static?void?IntersectPrototype()
- ????????{
-
????????????string[]?presidents?=?{?"Adams",?second.Count());
-
????????????IEnumerable<string>?concat?=?first.Concat(second);
-
????????????IEnumerable<string>?intersect?=?first.Intersect(second);
-
????????????Console.WriteLine("after?concat?element?count:{0}",?concat.Count());
-
????????????Console.WriteLine("after?intersect?element?count:{0}",?intersect.Count());
- ????????}
-
????????
-
返回的序列只包含位于第一个输入序列但不位于第二个输入序列的元素
-
- ????????static?void?ExceptPrototype()
- ????????{
-
????????????string[]?presidents?=?{?"Adams",?"Cleveland"?};
-
????????????Console.WriteLine("presidents?element?count:{0}",?presidents.Count());
-
????????????IEnumerable<string>?first?=?presidents.Take(4);
-
????????????Console.WriteLine("first?elements?count:{0}",?first.Count());
-
????????????IEnumerable<string>?except?=?presidents.Except(first);
-
????????????Console.WriteLine("after?except?element?count:{0}",?except.Count());
-
????????????foreach?(string?item?in?except)
- ????????????{
- ????????????????Console.WriteLine(item);
- ????????????}
- ????????}
-
????????#endregion
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|