Linq 统计DataTable数据
现有表A,结构如下(注意,a数据行不确定,可能是空,能有几行;name字段没有重复项的):
name count
------------
aaa 12
bbb 5
string[] arr={"aaa","bbb","ccc","ddd"};
问题:1.如果表A中name字段没有arr的项,就给表A填加一行,name为arr对应项,count为0,
有就不添加;
2.如果不进行第一步,如何快速的得出arr每个项对应的count值(不存在就为0)
不知道我的描述是否明白呢
[解决办法]
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Count", typeof(Int32));
DataRow dr1 = dt.NewRow();
dr1["Name"] = "aaa";
dr1["Count"] = 2;
dt.Rows.Add(dr1);
DataRow dr2 = dt.NewRow();
dr2["Name"] = "bbb";
dr2["Count"] = 2;
dt.Rows.Add(dr2);
DataRow dr3 = dt.NewRow();
dr3["Name"] = "ccc";
dr3["Count"] = 2;
dt.Rows.Add(dr3);
DataRow dr4 = dt.NewRow();
dr4["Name"] = "eee";
dr4["Count"] = 2;
dt.Rows.Add(dr4);
DataRow dr5 = dt.NewRow();
dr5["Name"] = "fff";
dr5["Count"] = 2;
dt.Rows.Add(dr5);
string[] arr = { "aaa", "bbb", "ccc", "ddd", "sss" };
var query = arr.Except(dt.AsEnumerable().Select(s => s.Field<string>("Name")).ToArray());
foreach (var item in query)
{
DataRow dr = dt.NewRow();
dr["Name"] = item;
dr["Count"] = 0;
dt.Rows.Add(dr);
}
ShareDB.DataTable dt=new ShareDB.DataTable(null,"select * from MyTable");
int iColName = dt.GetOrdinal("Name");
int iColCount = dt.GetOrdinal("Count");
for(int i=0,iCount=arr.Length;i<iCount;i++)
{
int iIndex=dt.IndexOf(iColName,arr[i]);
if(iIndex == -1)
{
dt.AddRow();
dt.SetValue(iColName,arr[i]);
dt.SetValue(iColCount,0);
}
else
{
dt.SetPos(iIndex);
int iGetCount = dt.GetInt(iColCount);
}
}
void Main()
{
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Count", typeof(Int32));
DataRow dr1 = dt.NewRow();
dr1["Name"] = "aaa";
dr1["Count"] = 2;
dt.Rows.Add(dr1);
DataRow dr2 = dt.NewRow();
dr2["Name"] = "bbb";
dr2["Count"] = 2;
dt.Rows.Add(dr2);
string[] arr = { "aaa", "bbb", "ccc", "ddd", "sss" };
var query= from a in arr
join t in dt.AsEnumerable()
on a equals t.Field<string>("Name") into left
from t in left.DefaultIfEmpty()
select string.Format("{0} -- {1}",a,t==null?0:t.Field<int>("Count")) ;
query.ToList().ForEach(q=>Console.WriteLine(q));
/*
aaa -- 2
bbb -- 2
ccc -- 0
ddd -- 0
sss -- 0
*/
}