如何解决以下问题:
var xvalue = from cust in list
where cust.DisplayString == ((Data)x).CustomerName
select cust.Number;
int namX = xvalue;
您的查询将始终返回匹配结果的“集合”,即使该集合仅返回一个项目。
如果您知道您的查询将始终只匹配一个项目,您可以使用 Single Linq 方法:
var xvalue = from cust in list
where cust.DisplayString == ((Data)x).CustomerName
select cust.Number;
int namX = xvalue.Single();
After returning a single item you should also get the property of the item which in this case is Number
var xvalue = from cust in list
where cust.DisplayString == ((Data)x).CustomerName
select cust.Number;
int namX = xvalue.Single().Number;
你有没有尝试过
int namX = Convert.ToInt32(namx.FirstOrDefault());
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();