C# 如何在数据表中选择不同的行并存储到数组中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1199176/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 10:42:32  来源:igfitidea点击:

How to select distinct rows in a datatable and store into an array

c#selectdatatabledistinct

提问by Ahmed Atia

I have a dataset objds. objds contains a table named Table1. Table1 contains column named ProcessName. This ProcessName contains repeated names.So i want to select only distinct names.Is this possible.

我有一个数据集 objds。objds 包含一个名为 Table1 的表。表 1 包含名为 ProcessName 的列。此 ProcessName 包含重复名称。所以我只想选择不同的名称。这可能吗?

  intUniqId[i] = (objds.Tables[0].Rows[i]["ProcessName"].ToString());

采纳答案by Thomas Levesque

DataView view = new DataView(table);
DataTable distinctValues = view.ToTable(true, "Column1", "Column2" ...);

回答by Martin Moser

DataTable dt = new DataTable();
dt.Columns.Add("IntValue", typeof(int));
dt.Columns.Add("StringValue", typeof(string));
dt.Rows.Add(1, "1");
dt.Rows.Add(1, "1");
dt.Rows.Add(1, "1");
dt.Rows.Add(2, "2");
dt.Rows.Add(2, "2");

var x = (from r in dt.AsEnumerable()
        select r["IntValue"]).Distinct().ToList();

回答by Ravedave

To improve the above answer: The ToTable function on dataview has a "distinct" flag.

改进上述答案:数据视图上的 ToTable 函数有一个“distinct”标志。

//This will filter all records to be distinct
dt = dt.DefaultView.ToTable(true);

回答by gideon

I just happened to find this: http://support.microsoft.com/default.aspx?scid=kb;en-us;326176#1

我碰巧发现了这个:http: //support.microsoft.com/default.aspx?scid=kb;en-us;326176#1

While looking for something similar, only, specifically for .net 2.0

在寻找类似的东西时,只针对 .net 2.0

Im assuming the OP was looking for distinct while using DataTable.Select(). (Select() doesn't support distinct)

我假设 OP 在使用 DataTable.Select() 时正在寻找不同的。(Select() 不支持distinct)

So here is the code from the above link:

所以这是上面链接中的代码:

class DataTableHelper 
{
    public DataTable SelectDistinct(string TableName, DataTable SourceTable, string FieldName)
    {   
        DataTable dt = new DataTable(TableName);
        dt.Columns.Add(FieldName, SourceTable.Columns[FieldName].DataType);

        object LastValue = null; 
        foreach (DataRow dr in SourceTable.Select("", FieldName))
        {
            if (  LastValue == null || !(ColumnEqual(LastValue, dr[FieldName])) ) 
            {
                LastValue = dr[FieldName]; 
                dt.Rows.Add(new object[]{LastValue});
            }
        }

        return dt;
    }

    private bool ColumnEqual(object A, object B)
    {

        // Compares two values to see if they are equal. Also compares DBNULL.Value.
        // Note: If your DataTable contains object fields, then you must extend this
        // function to handle them in a meaningful way if you intend to group on them.

        if ( A == DBNull.Value && B == DBNull.Value ) //  both are DBNull.Value
            return true; 
        if ( A == DBNull.Value || B == DBNull.Value ) //  only one is DBNull.Value
            return false; 
        return ( A.Equals(B) );  // value type standard comparison
    }
}

回答by Rahul

Following single line of code will avoid the duplicate rows of a DataTable:

以下单行代码将避免 a 的重复行DataTable

dataTable.DefaultView.ToTable(true, "employeeid");

Where:

在哪里:

  • first parameter in ToTable()is a booleanwhich indicates whether you want distinct rows or not.

  • second parameter in the ToTable()is the column name based on which we have to select distinct rows. Only these columns will be in the returned datatable.

  • in 的第一个参数ToTable()是一个布尔值,表示您是否想要不同的行。

  • 中的第二个参数ToTable()是列名,我们必须根据它选择不同的行。只有这些列将在返回的数据表中。

The same can be done from a DataSet, by accessing a specific DataTable:

DataSet通过访问特定的,可以从 a 完成相同的操作DataTable

dataSet.Tables["Employee"].DefaultView.ToTable(true, "employeeid");

回答by Zain Ali

With LINQ (.NET 3.5, C# 3)

使用 LINQ(.NET 3.5,C# 3)

var distinctNames = ( from row in DataTable.AsEnumerable()
 select row.Field<string>("Name")).Distinct();

 foreach (var name in distinctNames ) { Console.WriteLine(name); }

回答by ces2601

var distinctRows = (from DataRow dRow in dtInventory.Rows
                                select dRow["column_name"] ).Distinct();

var distinctRows = (from DataRow dRow in dtInventory.Rows
                                select dRow["col1"], dRow["col2"].. ).Distinct();

回答by Vijay Balani

Following works. I have it working for me with .NET 3.5 SP1

以下作品。我使用 .NET 3.5 SP1 为我工作

// Create the list of columns
String[] szColumns = new String[data.Columns.Count];
for (int index = 0; index < data.Columns.Count; index++)
{
    szColumns[index] = data.Columns[index].ColumnName;
}

// Get the distinct records
data = data.DefaultView.ToTable(true, szColumns);

回答by Dylan

var ValuetoReturn = (from Rows in YourDataTable.AsEnumerable()
select Rows["ColumnName"]).Distinct().ToList();