使用 linq 查询对象数组 [英] Query an object array using linq

查看:24
本文介绍了使用 linq 查询对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何查询对象数组.例如,我有一个像 CarList 这样的数组对象.所以 CarList[0] 会返回给我对象 Car.Car 具有 Model 和 Make 属性.现在,我想使用 linq 查询数组 CarList 以获取型号为bmw"的汽车的制造商.我尝试了以下

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;

我收到错误

找不到源类型 CarList[] 的查询模式的实现

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

我无法将 CarList 从数组更改为 List<> 之类的内容,因为 CarList 作为数组从网络服务返回给我.

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

请告诉我如何解决这个问题.如果你能用 C# 代码解释就好了.

Kindly let me know how this can be solved. Would be great if you can explain using C# code.

提前致谢.

推荐答案

添加:

using System.Linq;

到文件的顶部.

然后:

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);

注意事项:

  • select 子句中使用 item.Make 代替如果 s.Make 在你的代码中.
  • where 子句中的 item.Model 之间有一个空格
  • 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

这篇关于使用 linq 查询对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆