Linq根据IEnumerable属性选择

时间:2014-06-13 14:58:06

标签: c# linq

我有以下内容:

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

如果我的CarID = 4,如何使用linq获取CarName和Company名称。

我想我已经接近了.foreach(这是旧学校?)但是却迷失了它:

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}....

3 个答案:

答案 0 :(得分:2)

下面的代码返回匿名类实例,其中包含属性Cars,其中包含与此汽车匹配的汽车项目条件和Corps属性。

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

您可能希望将此匿名类替换为仅包含CarName和CompanyName的特定类。只需替换实例,如下所示:

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

此代码对于找到的汽车/公司数量是安全的。

答案 1 :(得分:1)

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

答案 2 :(得分:0)

你想找到任何一辆车与你的CarId =&gt;

匹配的公司
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);
}

根据Smudge的说明,如果你想确保你的CarId是唯一的,你可以考虑使用HashTable或类似的。