Get all column valus of a datatable based on only one distinct column [duplicate]

柔情痞子 提交于 2020-03-05 05:38:05

问题


I have a table with 10 columns and I want to get all values of each row but only of distinct IDs.

I have this so far:

DataTable Distinct = view.ToTable(true, "ID");

But this creates a DataTable that only contains the ID column. I want a DataTable with distinct ID's but containing all column values(there can be duplicates for the other columns.) Is there a simple way of doing this?


回答1:


One way would be to use LINQ for this job:

using System;
using System.Collections.Generic;
using System.Data;      
using System.Xml.Serialization;
using System.Linq;
using System.Data.Linq;
using System.Data.DataSetExtensions;

public class Program
{
    public static void Main()
    {
        using (DataTable dt = new DataTable("MyDataTable"))
        {
            // Add two columns.
            dt.Columns.Add("Id", typeof(int));
            dt.Columns.Add("Name", typeof(string));         

            // Add some test data.
            Random rnd = new Random();
            for(int i = 0; i < 7; i++)
            {
                DataRow dr = dt.NewRow();
                dr["Id"] = rnd.Next(1, 4);
                dr["Name"] = "Row-" + (i + 1);
                dt.Rows.Add(dr);
            }

            Console.WriteLine("All rows:");
            PrintResults(dt.AsEnumerable());

            var results = dt
                .AsEnumerable()
                .GroupBy(x => (int)x["Id"])
                .Select(g => g.First());

            Console.WriteLine("Distinct rows:");
            PrintResults(results);
        }
    }

    private static void PrintResults(IEnumerable<DataRow> rows)
    {
        foreach(var row in rows)
        {
            Console.WriteLine(
                String.Format(
                    "Id: {0}, Name: {1}", 
                    (int)row["Id"], 
                    (string)row["Name"]));
        }   
    }
}

dotnetfiddle



来源:https://stackoverflow.com/questions/25998500/get-all-column-valus-of-a-datatable-based-on-only-one-distinct-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!