1.lin语句
int[] nums = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0, 3 };
DataTable table = new DataTable("Numbers");
table.Columns.Add("number", typeof(int));
foreach (int n in nums)
{
table.Rows.Add(new object[] { n });
} var numbers = table.AsEnumerable();
var numberGroups =
from n in numbers
group n by n.Field<int>("number") into g
select new { Remainder = g.Key, Numbers = g }; foreach (var g in numberGroups)
{
Console.WriteLine("Numbers with a remainder of {0} when divided by 5:", g.Remainder);
foreach (var n in g.Numbers)
{
Console.WriteLine(n.Field<int>("number") + ",count:" + g.Numbers.Count());
}
} 2.比较器
public void Method{
var anagrams = testDS.Tables["Anagrams"].AsEnumerable(); var orderGroups = anagrams.GroupBy(w => w.Field<string>("anagram").Trim(), new AnagramEqualityComparer()); foreach (var g in orderGroups)
{
Console.WriteLine("Key: {0}", g.Key);
foreach (var w in g)
{
Console.WriteLine("\t" + w.Field<string>("anagram"));
}
}
} //创建一个比较器 private class AnagramEqualityComparer : IEqualityComparer<string>
{
public bool Equals(string x, string y)
{
return getCanonicalString(x) == getCanonicalString(y);
} public int GetHashCode(string obj)
{
return getCanonicalString(obj).GetHashCode();
} private string getCanonicalString(string word)
{
char[] wordChars = word.ToCharArray();
Array.Sort<char>(wordChars);
return new string(wordChars);
}
}