[英]How can I use a condition based on the queried data in an anonymous class in LINQ to DataSet?
I can do this by looping the result of a simplified query: 我可以通过循环简化查询的结果来做到这一点:
var query = from myrecord in dt.AsEnumerable()
where myrecord.Field<string>("field1") == "value1" || myrecord.Field<string>("field1") == "value2"
select myrecord;
foreach(var myrecord in query)
{
//if value1, then "X"
//sum += field2
}
But, I want to know if it's possible within the LINQ statement. 但是,我想知道LINQ语句中是否可行。
Anonymous class with two members: Name and Value. 具有两个成员的匿名类:名称和值。 Name is "X" or "Y" depending on field1 and Value is the sum of all field2 values for records where the conditions are met. 名称是“ X”或“ Y”,具体取决于字段1,值是满足条件的记录的所有字段2值的总和。 I think I need to use the Count() method, but I'm not sure how or where. 我想我需要使用Count()方法,但是我不确定如何或在哪里使用。 Maybe I need to use "group" and "into" to get the count from a temporary table? 也许我需要使用“ group”和“ into”来从临时表中获取计数?
If there are records with (field1 == "value1"), the string will be "X" else the string will be "Y". 如果存在带有(field1 ==“ value1”)的记录,则字符串将为“ X”,否则字符串将为“ Y”。
var query = from table in dt.AsEnumerable()
where table.Field<string>("field1") == "value1" ||
table.Field<string>("field1") == "value2"
select new
{
Name = (condition ? "X" : "Y"),
Value = //sum all field2 values
};
Thanks in advance! 提前致谢!
sure you can, Following sample works similarly 可以的,以下样本的工作原理类似
class Program
{
static void Main(string[] args)
{
List<Person> persons= new List<Person>();
var result = from p in persons
select new
{
Name = (s.IsMarried ? s.X : s.Y)
};
}
}
class Person
{
public bool IsMarried { get; set; }
public string X { get; set; }
public string Y { get; set; }
}
You just use the "table" variable that you already have. 您只需使用已有的“表”变量即可。
var query = from table in dt.AsEnumerable()
where table.Field<string>("field1") == "value1" ||
table.Field<string>("field1") == "value2"
select new
{
Name = (table.whatever ? "X" : "Y"),
Value = table.something.Sum()
};
您可以通过执行以下操作获得表的总和
table.Sum(t => t.ValueToSum) //Or whatever sub-table you need to sum
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.