Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query an object array using linq

Tags:

arrays

c#

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.

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

Thanks in advance.

like image 853
Derin Avatar asked Sep 07 '11 10:09

Derin


People also ask

Can LINQ query work with Array?

Yes it supports General Arrays, Generic Lists, XML, Databases and even flat files. The beauty of LINQ is uniformity.

How do I select a query in LINQ?

LINQ query syntax always ends with a Select or Group clause. The Select clause is used to shape the data. You can select the whole object as it is or only some properties of it. In the above example, we selected the each resulted string elements.

What is LINQ in C# with example?

Language-Integrated Query (LINQ) is the name for a set of technologies based on the integration of query capabilities directly into the C# language. Traditionally, queries against data are expressed as simple strings without type checking at compile time or IntelliSense support.


1 Answers

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
like image 154
Darin Dimitrov Avatar answered Oct 24 '22 02:10

Darin Dimitrov