2

如何解决以下问题:

var xvalue = from cust in list 
             where cust.DisplayString == ((Data)x).CustomerName 
             select cust.Number;
int namX = xvalue;
4

4 回答 4

5

您的查询将始终返回匹配结果的“集合”,即使该集合仅返回一个项目。

如果您知道您的查询将始终只匹配一个项目,您可以使用 Single Linq 方法:

var xvalue = from cust in list 
             where cust.DisplayString == ((Data)x).CustomerName 
             select cust.Number;
int namX = xvalue.Single();
于 2013-09-26T05:42:10.810 回答
0

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;
于 2013-09-26T05:45:04.270 回答
0

你有没有尝试过

int namX = Convert.ToInt32(namx.FirstOrDefault());
于 2013-09-26T05:43:02.810 回答
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();
于 2013-09-26T06:02:48.770 回答