Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Where with .Select Linq

I have a scenario where i have to use .Select with where in LINQ. Below is my query.

List<DTFlight> testList = _ctrFlightList.Select(i => new DTFlight() { AirLineName = i.AirLineName,ArrivalDate = i.ArrivalDate }).ToList();

I want ti use where(add condition) to this query.

Please Help... Thanks.

like image 741
Shivi Avatar asked Mar 17 '11 10:03

Shivi


People also ask

What is the use of select in LINQ?

LINQ Select operator is used to return an IEnumerable collection of items, including the data performed on the transformation of the method. By using Select Operator, we can shape the data as per our needs. In it, we can use two syntax types; let's see each method working flow.

How use contains in LINQ query?

LINQ Contains operator is used to check whether an element is available in sequence (collection) or not. Contains operator comes under Quantifier Operators category in LINQ Query Operators. Below is the syntax of Contains operator.

How can we retrieve data from database using LINQ in MVC?

Step 1: Right-click on the Models folder in the Solution Explorer then go to "Add" and click on "Class." Step 2: Choose "LINQ to SQL Classes" from the list and provide the name "User" for the dbml name.


3 Answers

I suggest you this use of Where :

List<DTFlight> testList = _ctrFlightList.
    Where(ctrFlight => ctrFlight.Property > 0).
    Select(i => new DTFlight() { AirLineName = i.AirLineName, ArrivalDate = i.ArrivalDate }).ToList();

Where returns a IEnumerable, so you can apply your Select on it.

like image 138
Nicolas Avatar answered Oct 06 '22 02:10

Nicolas


Simply add the Where before the Select:

List<DTFlight> testList =
    _ctrFlightList.Where(<your condition>)
                  .Select(i => new DTFlight() { AirLineName = i.AirLineName,
                                                ArrivalDate = i.ArrivalDate })
                  .ToList();
like image 44
Daniel Hilgarth Avatar answered Oct 06 '22 02:10

Daniel Hilgarth


What is the problem?

List<DTFlight> testList = _ctrFlightList.Where(p => p.ArrivalDate > DateTime.Now).Select(i => new DTFlight() { AirLineName = i.AirLineName,ArrivalDate = i.ArrivalDate }).ToList();

for example... What condition do you need?

like image 36
xanatos Avatar answered Oct 06 '22 03:10

xanatos