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

时间:2019-04-26 14:23:47

标签: c# entity-framework linq

目前,我正在使用Entity Framework和LINQ对应用程序进行编程。下面,我创建了方法CarsRow,该方法将不同的结果分配给属性。然后使用foreach循环填充列表。

当前所有内容都只能使用一个参数(在这种情况下为Cars)。

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

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

1 个答案:

答案 0 :(得分:1)

听起来好像您希望将所有Car中的Color中的the Cartesian Product作为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`
}