开发工具与关键技术:C#
作者:张俊辉
撰写时间:2019年05月28日
此示例使用Intersect创建一个包含两个int类型数组共享的公共值的序列。
通过for循环创建int类型数组num A,包含的数据为数值1到5;代码如下:
int[] numA = new int[5];
for (int i = 0; i < numA.Length; i++)
{
numA[i] = i+1;
Console.WriteLine(numA[i]);
}
输出如图:
通过for循环创建int类型数组numB,包含数据为数值1到10;代码如下:
int[] numB = new int[10];
for (int i = 0; i < numB.Length; i++)
{
numB[i] = i + 1;
Console.WriteLine(numB[i]);
}
输出结果如图:
使用Intersect创建一个包含两个int类型数组共享的公共值:
int[] num = numA.Intersect(numB).ToArray();
foreach (var n in num)
{
Console.WriteLine(n);
}
Console.ReadLine();
输出结果如图:
此示例使用Intersect创建一个序列,其中包含序列A和序列B的公共名称。
public void Intersect2()
{
List<A> a = new List<A>();
a.Add(new A { Name = "A" });
a.Add(new A { Name = "B" });
a.Add(new A { Name = "C" });
a.Add(new A { Name = "D" });
List<B> b = new List<B>();
b.Add(new B { Name = "C" });
b.Add(new B { Name = "D" });
b.Add(new B { Name = "E" });
b.Add(new B { Name = "F" });
var NameA = from p in a select p.Name;
var NameB = from c in b select c.Name;
var Name = NameA.Intersect(NameB);
foreach (var ch in Name)
{
Console.WriteLine(ch);
}
Console.ReadLine();
}
class A
{
public string Name { get; set; }
}
class B
{
public string Name { get; set; }
}
效果图如下: