foreach循环中的两种不同数据类型

问题描述 投票:1回答:1

目前我正在使用Entity Framework和LINQ编写应用程序。下面我创建了一个方法CarsRow,它为属性分配不同的结果。然后使用foreach循环填充列表。

目前一切只适用于一个参数(在这种情况下是Cars)。

问题:如何包含第二个参数(数据类型),然后用它填充列表carList。例如,Colors类。最后,应创建一个包含来自不同EF类的数据的Excel表。

private void Main()
{
    var rows = new List<ObjectContactsRow>();

    List<Cars> carList = new List<Cars>();

    carList = _ctx.Objekte.OrderBy(p => p.Nummer).ToList();

    //how can i integrate the data of class Colors in the loop together with the class Cars   

    foreach (var cars in carList)
    {
        var line = rows.Any() ? rows.Max(p => p.LineNumber) + 1 : 2;
        var newrow = CreateNewRow(cars, "parameter of type Colors", line);
        rows.Add(newrow);
    }

    CreateExcelFile(rows);
}

private CarsRow CreateNewRow(Cars obj, Colors col, int line)
{
    var objCars = obj.Cars;
    var colColor = col.Colors;

    return new CarsRow(line)
    {
        Cars = objCars,
        Colors = colColor,
    };
}
c# entity-framework linq
1个回答
1
投票

听起来你想要所有the Cartesian Products的Car与所有Colors作为ValueTuple<Car,Color>

要在Linq中执行任何两个列表中的笛卡尔积FooBar,请执行以下操作:

// (This approach uses the extension method syntax instead of the C# keywords `from`, `join`, etc)
// Type names have been added to lambda functions to make it obvious what the values are.

IEnumerable<Foo> fooValues = ...
IEnumerable<Bar> barValues = ...

IEnumerable< ( Foo, Bar ) > cartesianProduct = fooValues
    .SelectMany( Foo foo => barValues, ( Foo foo, Bar bar ) => /* the following syntax creates a new ValueTuple in C# 7: */ ( foo, bar ) );

// or more succinctly (removing unnecessary type names):
var cartesianProduct = fooValues
    .SelectMany( foo => barValues, ( foo, bar ) => ( foo, bar ) );

在你的情况下:

List<Car> cars = _ctx.Objekte
    .OrderBy( c => c.Nummer )
    .ToList();

List<Color> colors = // (you haven't shown how you get a List<Color>)

IEnumerable<(Car,Color)> cartesianProduct = cars
    .SelectMany( c => colors, ( car, color ) => ( car, color ) );

然后你可以直接迭代cartesianProduct - 但我不认为你需要,因为你的CarsRow对象与(Car,Color) ValueTuple对象相同,但是如果你想做额外的处理,那么你可以这样做:

foreach( (Car car, Color color) in cartesianProduct )
{
    // do stuff with `car` and `color`
} 
© www.soinside.com 2019 - 2024. All rights reserved.