开发者

querying a list - returns only one value

I have created a structure and list.

  public struct CarMake
{
    public string name;
    public string id;

}

I added structure objects to this (carMakers) and am trying to query

     string  selCar = from c in carMakers
                 where c.name == selectedCarMfgName
                 select c.id;

I am getting an error near selec开发者_Python百科t statement- cannont implicity convert IEnumerable to string. I know that query returns only one value, that's why I have like that.

thanks !


  string  selCar = (from c in carMakers
                     where c.name == selectedCarMfgName
                     select c.id).SingleOrDefault();

Your query returns a collection (with one element). You should use Single() (or SingleOrDefault()) to get that one item. If the query can return more than one result, you should look into First() ( or FirstOrDefault())


Pay attention to the error message. It probably says something like

"cannot implicitly convert IEnumerable<string> to string." 

The results of a query of a sequence is another sequence, an IEnumerable<T>. You may know that you expect only one result, but that's not what the query does. To obtain only one result, you can optionally include another extension method on the end.

yourQuery.First();
yourQuery.FirstOrDefault();
yourQuery.Single();
yourQuery.SingleOrDefault();

The difference in these is that the First* variations can work with sequenes with many elements, whereas the Single* variations will throw exceptions if more than one element is present. The *OrDefault variations support the concept of no matching elements, and returns the default value for the type (null in the case of classes, a default value (such as 0 for int) for structs).

Use the version that conforms to your expectation. If you expect one and only one match, prefer Single. If you only care about one out of arbitrarily many, prefer First.


        carMakers.Add(new CarMake() { name = "Audi", id = "1234" });
        string selCar =(from c in carMakers
                        where c.name == "Audi"
                        select c.id).FirstOrDefault();

Output- 1234


I would refactor my query slightly:

var selCar = carMakers.Single(c => c.name == selectedCarMfgName).id;

This assumes you know that the car is in the list. If not, use SingleOrDefault and check the return before getting the id.


I've not done too much with LINQ but because you are selecting into a string you may need to use FirstOrDefault as your statement could return back more than one value yet your string can only hold one.

First will return null value I think if nothing is found but FirstOrDefault will return you a blank string.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜