List<T>的交并差集操作操作

这个操作应该是比较基础的了,平时用得也比较少,所以写在这里提醒自己Framework已经提供了这样的功能了:

static void Main(string[] args)
{
var left = new List<SampleData> { SampleData.OwnedByLeft, SampleData.OwnedByBoth };
var right = new List<SampleData> { SampleData.OwnedByRight, SampleData.OwnedByBoth };

var intersection = left.Intersect(right);
Console.WriteLine("The intersection of left and right is: {0}", string.Join(",", intersection));//output: OwnedByBoth

var differenceSetOfLeft = left.Except(right);
Console.WriteLine("The difference set of left to right is: {0}", string.Join(",", differenceSetOfLeft));//output: OwnedByLeft

var differenceSetOfRight = right.Except(left);
Console.WriteLine("The difference set of right to left is: {0}", string.Join(",", differenceSetOfRight));//output: OwnedByRight

var unionSet = right.Union(left);
Console.WriteLine("The union set of left and right is: {0}", string.Join(",", unionSet));//output: OwnedByRight, OwnedByBoth, OwnedByLeft
}

private enum SampleData
{
OwnedByLeft,
OwnedByBoth,
OwnedByRight,
}

以上的示例中采用的是enum(同int),如果是对自定义的类型(如class、structure),则需要实现IEquatable<T>接口方能这样用。

posted @ 2011-10-20 11:54  _龙猫  阅读(231)  评论(0编辑  收藏  举报