仅基于一个不同的列获取数据表的所有列值 [英] Get all column valus of a datatable based on only one distinct column

查看:87
本文介绍了仅基于一个不同的列获取数据表的所有列值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含10列的表,我想获取每一行的所有值,但只获取不同的ID.

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

我到目前为止有这个:

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

但这会创建一个仅包含ID列的DataTable.我想要一个具有唯一ID但包含所有列值的DataTable(其他列可以重复).是否有一种简单的方法?

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?

推荐答案

一种方法是使用 LINQ 进行此工作:

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

这篇关于仅基于一个不同的列获取数据表的所有列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆