删除没有一列的重复行

时间:2015-10-18 10:20:22

标签: c# linq

我有这样的DataTable:

Headache|Nausea|Temp  |Flu
no      |no    |normal|no
yes     |no    |high  |yes
yes     |yes   |high  |yes
yes     |no    |normal|no
no      |no    |high  |no
no      |no    |high  |yes

我想删除没有一列(Flu)的所有重复行:

no      |no    |high  |no
no      |no    |high  |yes

并得到结果:

Headache|Nausea|Temp  |Flu
no      |no    |normal|no
yes     |no    |high  |yes
yes     |yes   |high  |yes
yes     |no    |normal|no

如何使用linq实现这一目标?

1 个答案:

答案 0 :(得分:1)

尝试这样的事情

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Headache", typeof(string));
            dt.Columns.Add("Nausea", typeof(string));
            dt.Columns.Add("Temp", typeof(string));
            dt.Columns.Add("Flu", typeof(string));

            dt.Rows.Add(new string[] {"no", "no" ,"normal", "no"});
            dt.Rows.Add(new string[] {"yes", "no" ,"high", "yes"});
            dt.Rows.Add(new string[] {"yes", "yes" ,"high", "yes"});
            dt.Rows.Add(new string[] {"yes", "no" ,"normal", "no"});
            dt.Rows.Add(new string[] {"no", "no" ,"high", "no"});
            dt.Rows.Add(new string[] {"no", "no" ,"high", "yes"});

            var dict = dt.AsEnumerable()
                .GroupBy(x => new { Headache = x.Field<string>("Headache"), Nausea = x.Field<string>("Nausea"), Temp = x.Field<string>("Temp") }, y => y)
                .ToDictionary(x => x.Key, y => y.ToList());

            DataTable dt2 = dict.Where(x => x.Value.Count == 1).SelectMany(y => y.Value).CopyToDataTable();

            //or simply this
            DataTable dt3 = dt.AsEnumerable()
                .GroupBy(x => new { Headache = x.Field<string>("Headache"), Nausea = x.Field<string>("Nausea"), Temp = x.Field<string>("Temp") })
                .Where(x => x.Count() == 1).SelectMany(y => y).CopyToDataTable();

        }
    }
}
​