zoukankan      html  css  js  c++  java
  • Linq分组

    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("	" + 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);
                    }
                }

      

  • 相关阅读:
    01-节点层次
    WebAPI02
    WebAPI01
    牛客剑指Offer7
    Python字典排序
    Python字典中的键映射多个值
    计算机硬件的主要技术指标
    计算机的基本组成
    计算机系统概论
    数据库概论
  • 原文地址:https://www.cnblogs.com/mawenzhu/p/4940743.html
Copyright © 2011-2022 走看看