我有一个带有两列的数据表“tblFields”,它的值如下。
FieldId FieldValue
------- ----------
0_Name test0
0_Amount 100
1_Name test1
1_Amount 100
2_Name test2
2_Amount 200
3_Name test3
3_Amount 0.00
4_Name test4
4_Amount
下面的linq为我提供了数据表中不以“0_”开头的所有行。现在我需要对此集合应用过滤器以获取金额(_Amount)不等于0.00或空的唯一行。此外,当_Amount等于0.00或为空时,它应该排除_Name行。
var pairs = from row in tblFields.AsEnumerable()
where !row.Field<string>("FieldId").StartsWith("0_")
select new
{
key = GetId(row.Field<string>("FieldId")),
value = row.Field<string>("FieldValue")
};
我正在寻找如下输出。是否有可能使用linq获得此结果?有没有人知道任何其他方法来实现这一目标?谢谢你的任何想法。
1_Name test1
1_Amount 100
2_Name test2
2_Amount 200
答案 0 :(得分:1)
这应该有效(假设Field<T>
方法返回类型T并且它适用于数字类型):
var pairs = from row in tblFields.AsEnumerable()
where !row.Field<string>("FieldId").StartsWith("0_")
let value = row.Field<decimal>("FieldValue")
where value != 0.00M
select new
{
Id = row.Field<string>("FieldId"),
Value = value
}
如果Field<T>
方法不适用于数字类型,请尝试以下操作:
var pairs = from row in tblFields.AsEnumerable()
where !row.Field<string>("FieldId").StartsWith("0_")
let fieldValueString = row.Field<string>("FieldValue")
let value = String.IsNullOrEmpty(fieldValueString)? 0M : Decimal.Parse(fieldValueString)
where value != 0.00M
select new
{
Id = row.Field<string>("FieldId"),
Value = value
}
这里应删除字段ID和值,但格式略有不同(但仍然很简单):
var pair= from row in tblFields.AsEnumerable()
group row by row.Field<string>("FieldId")[0] into idValueGroup
where idValueGroup.Key != "0"
select new
{
IdLine = idValueGroup.ElementAt(0),
ValueLine = idValueGruop.ElementAt(1)
} into linePair
where linePair.ValueLine.Field<decimal>("FieldValue") != 0.00M
select new
{
NameId = linePair.IdLine.Field<string>("FieldId"),
Name = linePair.IdLine.Field<string>("FieldValue"),
ValueId = linePair.ValueLine.Field<string>("FieldId"),
Value = linePair.ValueLine.Field<decimal>("FieldValue")
}
答案 1 :(得分:0)
你可以这样做
var pairs = from row in tblFields.AsEnumerable()
where !row.Field<string>("FieldId").StartsWith("0_")
&& row.Field<string>("FieldValue") != "0.00"
select new
{
key = GetId(row.Field<string>("FieldId")),
value = row.Field<string>("FieldValue")
};
public class MyObject
{
public string FieldId { get; set; }
public string FieldValue { get; set; }
}
List<MyObject> list = new List<MyObject> {
new MyObject { FieldId = "0_Name", FieldValue = "test0"},
new MyObject { FieldId = "1_Name", FieldValue = "test1" },
new MyObject { FieldId = "2_Name", FieldValue = "test2" }
};
var pairs = from row in list
where !row.FieldId.StartsWith("0_")
&& row.FieldValue != "0.00")
select new
{
key = row.FieldId,
value = row.FieldValue
};