以COUNT作为条件在DataTable上执行选择 [英] Perform a Select on a DataTable with a COUNT as a condition

查看:91
本文介绍了以COUNT作为条件在DataTable上执行选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个DataTable,我想对ID列中正好有3个条目的所有结果执行选择查询。



示例:

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("...??





我想只返回aa行,因为bb有4个条目而cc只有1个。



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

推荐答案

请找到解决方案,测试其工作情况。



Please find the Solution, Tested its working.

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();


       }





如果您有更多期待,请告诉我你是完全必需的。我在这里使用Linq查询从DataTable中获取数据。



谢谢!



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!


这篇关于以COUNT作为条件在DataTable上执行选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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