开发者

Query an object array using linq

开发者 https://www.devze.com 2023-04-02 21:48 出处:网络
I would like to know how can I query an array of objects. For example 开发者_高级运维I have an array object like CarList. So CarList[0] would return me the object Car. Car has properties Model and Mak

I would like to know how can I query an array of objects. For example 开发者_高级运维I have an array object like CarList. So CarList[0] would return me the object Car. Car has properties Model and Make. Now, I want to use linq to query the array CarList to get the Make of a Car whose Model is say "bmw". I tried the following

var carMake = from item in CarList where item .Model == "bmw" select s.Make;

I get the error

Could not find an implementation of the query pattern for source type CarList[]

I cannot change CarList from array to something like List<> since CarList is retured to me as array from a webservice.

How can this be solved?


Add:

using System.Linq;

to the top of your file.

And then:

Car[] carList = ...
var carMake = 
    from item in carList
    where item.Model == "bmw" 
    select item.Make;

or if you prefer the fluent syntax:

var carMake = carList
    .Where(item => item.Model == "bmw")
    .Select(item => item.Make);

Things to pay attention to:

  • The usage of item.Make in the select clause instead if s.Make as in your code.
  • You have a whitespace between item and .Model in your where clause
0

精彩评论

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