从数据表中获取不同的值

时间:2011-10-20 09:26:13

标签: c# linq

我有DataTable值:

ID  NameID  Name
1   1       qwe
2   2       ert  
3   2       ert  
4   3       dffg 
5   3       dffg

我希望得到一个包含不同行的DataTable

ID  NameID  Name
1   1       qwe
2   2       ert
4   3       dffg 

如何使用LINQ或其他方法实现这一目标?

3 个答案:

答案 0 :(得分:1)

var rows = tbl.AsEnumerable().Select(row => row).ToList();
tbl = new DataTable();
tbl.Columns.Add("ID", typeof(Int32));
tbl.Columns.Add("NameID", typeof(Int32));
tbl.Columns.Add("Name", typeof(String));

rows.GroupBy(r => r.Field<int>("NameID"))                
    .Select(rr => rows.First(rw => rw.Field<Int32>("NameID") == rr.Key))
    .ToList()
    .ForEach(rname => tbl.Rows.Add(new object []
        {                                                 
            rname.Field<Int32>("ID"),
            rname.Field<Int32>("NameID"),
            rname.Field<String>("Name"),                    
        }));

测试数据设置:

DataTable tbl = new DataTable();
tbl.Columns.Add("ID", typeof (Int32));
tbl.Columns.Add("NameID", typeof (Int32));
tbl.Columns.Add("Name", typeof (String));

tbl.Rows.Add(new object[] { 1, 1, "qwe" });
tbl.Rows.Add(new object[] { 2, 2, "ert" });
tbl.Rows.Add(new object[] { 3, 2, "ert" });
tbl.Rows.Add(new object[] { 4, 3, "dffg" });
tbl.Rows.Add(new object[] { 5, 3, "dffg" });

答案 1 :(得分:0)

将数据表分配给数据视图,使用dataview对象,我们可以使用RowFilter,如下所示。

                Dim DTb As New DataTable()
                DataView dView= new DataView(DTb); 
                dView.RowFilter = strCondition.ToString //strCondition contains the condition to filter

strCondition将包含要过滤的条件,并在过滤后将数据视图重新分配给数据表,如下所示

                DTb = dView.ToTable()

答案 2 :(得分:0)

尝试,

 var result = from ele in dt.AsEnumerable()
               group ele by ele["NameID"] into g
               select g.FirstOrDefault();

  foreach (var t in result)
     Console.WriteLine(t[0] + " " + t[1] + " " + t[2]);