我需要一些帮助才能从一个列表中获取值并将其分配给另一个列表。我已经创建了我正在做的简化版本。
鉴于以下内容:
namespace ConsoleApplication1
{
class Car
{
public Car(string maker)
{
this.maker = maker;
this.counter = 0;
}
public string maker { get; set; }
public int counter { get; set; }
}
class CarModel
{
public CarModel(string maker, string model)
{
this.maker = maker;
this.model = model;
}
public string maker { get; set; }
public string model { get; set; }
}
class Program
{
static void Main(string[] args)
{
List<Car> carList = new List<Car>();
carList.Add(new Car("Honda"));
carList.Add(new Car("Toyota"));
carList.Add(new Car("Nissan"));
carList.Add(new Car("Ford"));
carList.Add(new Car("Dodge"));
List<CarModel> modelList = new List<CarModel>();
modelList.Add(new CarModel("Honda", "Accord"));
modelList.Add(new CarModel("Honda", "Civic"));
modelList.Add(new CarModel("Honda", "Pilot"));
modelList.Add(new CarModel("Ford", "F150"));
modelList.Add(new CarModel("Ford", "F250"));
modelList.Add(new CarModel("Ford", "Edge"));
modelList.Add(new CarModel("Ford", "Fusion"));
modelList.Add(new CarModel("Nissan", "GT-R"));
modelList.Add(new CarModel("Nissan", "Versa"));
modelList.Add(new CarModel("Dodge", "Ram"));
var grouped = modelList.GroupBy(s => s.maker, (key, values) => new { Maker = key, Count = values.Count() });
foreach (var i in grouped)
{
foreach (Car car in carList)
{
if (i.Maker == car.maker)
{
car.counter = i.Count;
}
}
}
foreach (Car car in carList)
{
Console.WriteLine(car.maker + " | " + car.counter.ToString());
}
}
}
}
我从分组变量中获取Count值,并通过maker字段中的相等将其赋值给Car对象。
我正在使用的ForEach循环很好地处理了赋值,但我知道当每个列表的项数增加时,循环将花费更长的时间来执行。
我得到的结果如下(这是我要求的)
Honda | 3
Toyota | 0
Nissan | 2
Ford | 4
Dodge | 1
我相信会有更好的方法来做到这一点。我查看了Intersect方法,但这样做仍然需要我遍历列表来分配值。
我尝试在列表中进行外连接,例如:
var combined = from a in carList
from b in grouped
.Where(bOuter => bOuter.Maker == a.maker)
.DefaultIfEmpty()
select new
{
maker = a.maker,
count = b.Count
};
foreach (var i in combined)
{
Console.WriteLine(i.maker + " - " + i.count);
}
但是我收到了Null Exception错误。
感谢任何意见/建议。
答案 0 :(得分:0)
您需要的是逻辑。您想为每个Car maker设置该列表中的模型数量。因此,对于每个汽车制造商,计数器将等于来自modelList的所有汽车,其中制造商等于carList中的制造商。确保还使用System.Linq&#34;&#34;
foreach(Car carObject in carList)
{
carObject.counter = modelList.Where(x => x.maker == carObject.maker).ToList().Count;
}