Query an object array using linq

后端 未结 1 1637
别那么骄傲
别那么骄傲 2020-12-05 02:02

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 M

相关标签:
1条回答
  • 2020-12-05 02:19

    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 讨论(0)
提交回复
热议问题