Gina Marano
Gina Marano

Reputation: 1813

Linq select based on IEnumerable property

I have the following:

IEnumerable<Corporations> Corps = ...

public class Corporation
{
    public string CompanyName { get; set; }
    public virtual ICollection<Cars> Cars { get; set; }
}

public class Car
{
    public int CarID { get; set; }
    public string CarName { get; set; }
}

If I have the CarID = 4, how do I get CarName and Company name using linq.

I think I have come close with the .foreach (which is old school?) but get lost closing it:

var result = Corps.Where(cps => cps.Cars != null).ToList()
                .ForEach(x => x.Cars.ToList()
                    .ForEach(cr => cr.CarID == 5)
                        .Select (@y => new { FoundCorp = x.CompanyName, FoundCar = cr.CarName}....

Upvotes: 0

Views: 763

Answers (3)

Suraj Singh
Suraj Singh

Reputation: 4069

 var check = Corporation.SelectMany(p => p.Cars.Where(m => m.CarID  == "4").Select(n => new
            {
                n.CarName,
                p.CompanyName
            }));

Upvotes: 1

Stan
Stan

Reputation: 1999

The code below returns anonymous class instances, with property Cars containing car item matching conditon and Corps property for this car found.

var results = Corps
    .SelectMany(corp => corp.Cars, (corps, cars) => new { Corps = corps, Cars = cars })
    .Where(item => item.Cars.CarID == 4)
;

foreach (var item in results)
{
    Console.WriteLine("Car with id {0} have found in for company {1}", item.Cars.CarID, item.Corps.CompanyName);
}

You might want to replace this anonymous class with some particular that holds only CarName and CompanyName. Just replace the instantiation as below:

var results = Corps
    .SelectMany(corp => corp.Cars, (corps, cars) => new SomeResult(corps.CompanyName, cars.CarName))
    .Where(item => item.Cars.CarID == 4)
;

This code is safe to number of cars/companies found.

Upvotes: 2

Jonesopolis
Jonesopolis

Reputation: 25370

you want to find the corp where any car matches your CarId =>

int carid = 1;
var corp = Corps.FirstOrDefault(corp => corp.Cars.Any(car => car.CarID == carid));

if (Corp != null)
{
    Console.WriteLine(Corp.CompanyName);
    Console.WriteLine(Corp.Cars.First(car => car.CarID == carid).CarName);
}

As per Smudge's notes, you may consider using a HashTable or similar if you want to ensure your CarId's are unique.

Upvotes: 0

Related Questions