Click here to Skip to main content
15,884,298 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a DataTable that I want to perform a Select query on for all results that have exactly 3 entries within the ID column.

Example:
DataTable table = new DataTable();
table.Columns.Add("ID",typeof(string));
table.Columns.Add("value",typeof(double));

table.Rows.Add("aa",1);
table.Rows.Add("aa",1);
table.Rows.Add("aa",1);
table.Rows.Add("bb",1);
table.Rows.Add("bb",1);
table.Rows.Add("bb",1);
table.Rows.Add("bb",1);
table.Rows.Add("cc",1);

DataTable newTable = table.Select("...??


I want to return only the "aa" rows since the "bb" has 4 entries and "cc" has only 1.
Posted

1 solution

Please find the Solution, Tested its working.

C#
static void Main(string[] args)
       {

           DataTable table = new DataTable();
           table.Columns.Add("ID", typeof(string));
           table.Columns.Add("value", typeof(double));

           table.Rows.Add("aa", 1);
           table.Rows.Add("aa", 1);
           table.Rows.Add("aa", 1);
           table.Rows.Add("bb", 1);
           table.Rows.Add("bb", 1);
           table.Rows.Add("bb", 1);
           table.Rows.Add("bb", 1);
           table.Rows.Add("cc", 1);

           var tblData = from rowData in table.AsEnumerable()
                         where rowData.Field<string>("ID") == "aa"
                         select rowData;


           Console.WriteLine("ID" + " : " + "value");
           Console.WriteLine("------------");
           foreach (var item in tblData)
           {
               Console.WriteLine(item.Field<string>("ID").ToString() + " : " + item.Field<double>("value").ToString());
           }

           Console.WriteLine("\n\n");

           var tblDatas = from rowData in table.AsEnumerable()
                         group rowData by rowData.Field<string>("ID") into groupResult
                         where groupResult.Count() == 3
                         select new { ID = groupResult.Key, value = groupResult };





           Console.WriteLine("ID Value with 3 Rows" );
           Console.WriteLine("------------");
           foreach (var item in tblDatas)
           {
               Console.WriteLine(item.ID);
           }

           Console.ReadLine();


       }


If you are expecting more, let me know what you are exactly required. I used Linq query here to fetch the data from DataTable.

Thanks!
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900