using System;
using static System.Console;
using System.Collections.Generic; // for IEnumerable<T>
using System.Linq; // for LINQ extension methods
namespace LinqWithSets
{
class Program
{
static void Output(IEnumerable<string> cohort,
string description = "")//输出字符串集合
{
if (!string.IsNullOrEmpty(description))
{
WriteLine(description);
}
Write(" ");
WriteLine(string.Join(", ", cohort.ToArray()));
}
/*
Cohort 1
Rachel, Gareth, Jonathan, George
Cohort 2
Jack, Stephen, Daniel, Jack, Jared
Cohort 3
Declan, Jack, Jack, Jasmine, Conor
cohort2.Distinct():
Jack, Stephen, Daniel, Jared
cohort2.Union(cohort3):
Jack, Stephen, Daniel, Jared, Declan, Jasmine, Conor
cohort2.Concat(cohort3):
Jack, Stephen, Daniel, Jack, Jared, Declan, Jack, Jack, Jasmine, Conor
cohort2.Intersect(cohort3):
Jack
cohort2.Except(cohort3):
Stephen, Daniel, Jared
cohort1.Zip(cohort2):
Rachel matched with Jack, Gareth matched with Stephen, Jonathan matched with Daniel, George matched with Jack
*/
static void Main(string[] args)
{
var cohort1 = new string[]
{ "Rachel", "Gareth", "Jonathan", "George" };
var cohort2 = new string[]
{ "Jack", "Stephen", "Daniel", "Jack", "Jared" };
var cohort3 = new string[]
{ "Declan", "Jack", "Jack", "Jasmine", "Conor" };
Output(cohort1, "Cohort 1");
Output(cohort2, "Cohort 2");
Output(cohort3, "Cohort 3");
WriteLine();
Output(cohort2.Distinct(), "cohort2.Distinct():");//通过使用默认的相等比较器比较值,从序列中返回不同的元素。
WriteLine();
Output(cohort2.Union(cohort3), "cohort2.Union(cohort3):");//使用默认的相等比较器生成两个序列的集合并集
WriteLine();
Output(cohort2.Concat(cohort3), "cohort2.Concat(cohort3):");//连接两个序列。
WriteLine();
Output(cohort2.Intersect(cohort3), "cohort2.Intersect(cohort3):");//通过使用默认相等比较器比较值来生成两个序列的集合交集。
WriteLine();
Output(cohort2.Except(cohort3), "cohort2.Except(cohort3):");//通过使用默认的相等比较器比较值来产生两个序列的集合差异。
WriteLine();
//将指定函数应用于两个序列的相应元素,产生结果序列。
Output(cohort1.Zip(cohort2, (c1, c2) => $"{c1} matched with {c2}"),
"cohort1.Zip(cohort2):");
ReadLine();
}
}
}
【C#】working with sets and bags using LINQ
猜你喜欢
转载自blog.csdn.net/cxyhjl/article/details/130241558
今日推荐
周排行