基本上我正在做一些工作来填充数据表。然后,一旦我有了数据表,我就会得到我的结果。那么我想要做的是根据这些结果从原始数据表中选择。我下面的代码是失败的,所以任何帮助都会很棒。第二部分我很好奇,是如何返回一个集合来迭代选择
谢谢!
DataTable invoicesDataTable = null;
try
{
invoicesDataTable = GetInvoiceIds();
}
catch (Exception ex)
{
}
//new work here
var uniqueCountryCustomer =
invoicesDataTable
.AsEnumerable()
.GroupBy(row => new
{
Department = (string)row["Department"],
Attorney = (string)row["MatterNumber"],
MatterNo = (string)row["CUSTOMERNAME"]
});
string depart = string.Empty;
string attorn = string.Empty;
string MatNo = string.Empty;
for (int i = 0; i < uniqueCountryCustomer.ToArray().Length; i++)
{
var results =
from myRow in invoicesDataTable.AsEnumerable()
where myRow.Field<string>("Department") == uniqueCountryCustomer.ToArray()[i].ToString()
&& myRow.Field<string>("MatterNumber") == uniqueCountryCustomer.ToArray()[i].ToString()
&& myRow.Field<string>("CUSTOMERNAME") == uniqueCountryCustomer.ToArray()[i].ToString()
select myRow;
//now do work on each of these rows from the group
}
答案 0 :(得分:1)
我不使用数据表...永远,真的。但你不能这样做:
DataTable invoicesDataTable = null;
try
{
invoicesDataTable = GetInvoiceIds();
}
catch (Exception ex)
{
}
//new work here
var uniqueCountryCustomer =
invoicesDataTable
.AsEnumerable()
.GroupBy(row => new
{
Department = (string)row["Department"],
Attorney = (string)row["MatterNumber"],
MatterNo = (string)row["CUSTOMERNAME"]
});
foreach(var customerGroup in uniqueCountryCustomer)
{
foreach(var row in customerGroup)
{
//now do work on each of these rows from the group
}
}
是否有某些原因需要在分组后再次从表中获取行?
答案 1 :(得分:1)
GroupBy有三个部分: 1)选择密钥 2)选择值 3)如何投影键/值
这里有相当不错的例子:https://msdn.microsoft.com/en-us/library/vstudio/bb534493(v=vs.100).aspx
var uniqueCountryCustomer =
invoicesDataTable
.AsEnumerable()
.GroupBy(Key => new
{
Department = (string)row["Department"],
Attorney = (string)row["MatterNumber"],
MatterNo = (string)row["CUSTOMERNAME"]
},Vals => new {
something1 = ...,
something2 = ...
},(Key,Vals)=>new {
Key=Key,
Sum=vals.Select(v=>v.something1).Sum(),
//If you need these
Max=vals.Select(v=>v.something1).Max(),
Min=vals.Select(v=>v.something1).Min(),
Vals=Vals
});
foreach(var customer in uniqueCountryCustomer)
{
... Do stuff ...
Console.Writeline("Customer {0} owes us a total of {1}",customer.Key.MatterNo,customer.Sum);
foreach(var things in customer)
{
Console.Writeline("...Bill:{0}",var.something1);
}
}
答案 2 :(得分:0)
我认为这段代码失败了:
var results =
from myRow in invoicesDataTable.AsEnumerable()
where myRow.Field<string>("Department") == uniqueCountryCustomer.ToArray()[i].ToString()
&& myRow.Field<string>("MatterNumber") == uniqueCountryCustomer.ToArray()[i].ToString()
&& myRow.Field<string>("CUSTOMERNAME") == uniqueCountryCustomer.ToArray()[i].ToString()
select myRow;
您将每个字段与可能不正确的相同值进行比较。
也许您可以将ToString()
替换为Department
,依此类推?您在GroupBy
表达式中使用的那些值?!