将数据表中的重复行数添加到新列

时间:2014-02-25 10:11:58

标签: c#

我需要识别表中的重复列,并添加一个包含重复列数的新列。提前致谢 这是需要编辑的表。

enter image description here

结果表:

enter image description here

4 个答案:

答案 0 :(得分:1)

在SQL中,尝试这样的事情:

SELECT FirstName, COUNT(*) FROM FirstNames GROUP BY FirstName

答案 1 :(得分:1)

如果您想要LinQ,并且记得要在文件顶部使用System.Linq;,请尝试以下操作:

class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            string[] data = new String[] {"john","john","mike","ann","ann","ann"};

            var results = data.GroupBy(x => x).Select(g => new {name = g.Key, count = g.Count()});

            foreach (var result in results)
            {
                Console.WriteLine("{0} occurred {1} times...", result.name, result.count);
            }


            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }
    }

答案 2 :(得分:0)

你可以试试这个

void tables()
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[1] { new DataColumn("Name") });
        dt.Rows.Add("John");
        dt.Rows.Add("Mike");
        dt.Rows.Add("Ann");
        dt.Rows.Add("Sam");
        DataTable dt1 = new DataTable();
        dt1.Columns.AddRange(new DataColumn[1] { new DataColumn("Name") });
        dt1.Rows.Add("John");
        dt1.Rows.Add("John");
        dt1.Rows.Add("Mike");
        dt1.Rows.Add("Ann");
        dt1.Rows.Add("Ann");
        dt1.Rows.Add("Ann");
        DataTable dt2 = new DataTable();
        dt2.Columns.AddRange(new DataColumn[3] { new DataColumn("Name"), new DataColumn("Available"), new DataColumn("Count") });
        int count = 0;
        foreach (DataRow r in dt.Rows)
        {
            count = dt1.Select("Name='" + r[0].ToString() + "'").Count();
            if (count > 0)
                dt2.Rows.Add(r[0].ToString(), "available", count.ToString());
            else
                dt2.Rows.Add(r[0].ToString(), "unavailable", count.ToString());
        }
    }

答案 3 :(得分:0)

在LINQ中:

table.GroupBy (t => t.Name).Select (t => new {Name = t.Key, Count = t.Count ()})

假设:

  • table是包含您的第一张表的集合
  • Name是包含名称
  • 的列的名称