如何解决以下问题:
var xvalue = from cust in list
where cust.DisplayString == ((Data)x).CustomerName
select cust.Number;
int namX = xvalue;
答案 0 :(得分:5)
您的查询将始终返回匹配结果的“集合”,即使该集合仅返回单个项目。
如果您知道您的查询总是只匹配一个项目,则可以使用Single Linq方法:
var xvalue = from cust in list
where cust.DisplayString == ((Data)x).CustomerName
select cust.Number;
int namX = xvalue.Single();
答案 1 :(得分:0)
你试过吗
int namX = Convert.ToInt32(namx.FirstOrDefault());
答案 2 :(得分:0)
返回单个项目后,您还应获取该项目的属性,在本例中为Number
var xvalue = from cust in list
where cust.DisplayString == ((Data)x).CustomerName
select cust.Number;
int namX = xvalue.Single().Number;
答案 3 :(得分:0)
if u are sure that the condition "cust.DisplayString == ((Data)x).CustomerName" will return only one record than u can use code below this will return one number. other wise please see the next tip.
int namX = (from cust in list
where cust.DisplayString == ((Data)x).CustomerName
select cust).ToList().FirstOrDefault().Number;
if after applying the condition results can be more than one than surely it will be a list of int so the below code will work.
List<int> namX = (from cust in list
where cust.DisplayString == ((Data)x).CustomerName
select cust.Number).ToList();