2017-09-28 34 views
-3

enter image description here如何在數據表中篩選某些數據行

我有一個數據表像上面的,什麼是過濾行

的有效途徑
  1. Col1中,col2的,COL3,COL4應與其它行匹配(一個或多個)
  2. COL5不同

類似下面,

enter image description here

如何提取其中由COL5

感謝

+0

來過濾他們的DataGridView?你的意思是刪除前4列的重複? – Slai

+0

@Slai我想提取其中4個值相匹配的數據行和第五列的值而變化 – karthik

回答

1

我認爲你可以使用ToTable System.Data.DataView的(不同,列)方法。下面是代碼示例:

DataView view = new DataView(table); 
DataTable distinctValues = view.ToTable(true, "Col1", "Col2" ,"Col3","Col4","Col5"); 
+0

相信上面的代碼返回基於5列唯一行。我需要這樣的東西4列匹配和COL5值不同.... – karthik

+0

你想找到的列有不同的價值觀? – MSL

+0

@MSL我需要它Col1,2,3,4匹配與其他行的數據行,但COL5不同... – karthik

-2

我的猜測是一如既往地與C#中最有效的與數據表是使用LINQ的不同行:

var consolidatedChildren = 
from c in children 
group c by new 
{ 
    c.Col1, 
    c.Col2, 
    c.Col3, 
    c.Col4 
} into gcs 
select new ConsolidatedChild() 
{ 
    Col1= gcs.Key.Col1, 
    Col2= gcs.Key.Col2, 
    Col3= gcs.Key.Col3, 
    Col4= gcs.Key.Col4, 
    Col5= gcs.ToList(), 
}; 

雖然我不是100%肯定這將返回COL5,但應該有辦法做到這一點使用LINQ。

編輯:使用兒童應該更容易/更清潔。

-1

運行此,看到了kdr

var groups = dt.AsEnumerable().GroupBy(x => new { col1 = x["col1"], col2 = x["col2"], col3 = x["col3"], col4 = x["col4"] }); 

foreach (var group in groups) 
{ 
    var k = group.Key; 

    foreach (var dr in group) 
    { 
    } 
} 
1
// DataTable dt = new DataTable(); for (int i = 1; i < 6; i++) dt.Columns.Add("Col" + i); 
// foreach (var c in "EEFG") dt.Rows.Add(("A B C D " + c).Split()); // optional to generate the table 

dt = dt.Rows.Cast<DataRow>() 
    .GroupBy(r => Tuple.Create(r[0], r[1], r[2], r[3]))   // group by the first 4 values in each row (you can replace the numbers with the indexes or names of your columns) 
    .SelectMany(g => g.GroupBy(r => r[4], (k, v) => v.First())) // group each group by the 5th value, and select the first row in each group, to get the distinct rows 
    .CopyToDataTable();           // optional to copy the rows to a new DataTable 

Debug.Print(string.Join("\n", dt.AsEnumerable().Select(r => string.Join("\t", r.ItemArray)))); // optional to print the result 

如果沒有其他列,它可以縮短到讓每個不同行組:

dt = dt.Rows.Cast<DataRow>().GroupBy(r => Tuple.Create(r[0], r[1], r[2], r[3])) 
    .SelectMany(g => g.Distinct(DataRowComparer.Default)).CopyToDataTable();