如何在C#中编辑匿名动态列表

时间:2019-01-04 16:06:22

标签: c# dynamic

我正在尝试创建一个动态列表以在单个方法中充当内存中的工作表。我从linq到sql创建的动态列表具有一个额外的属性(NewStatusId),稍后我将使用相同的方法对其进行更新。此方法是一次性的,因此为此创建一个特定的对象类没有任何意义。

如何获得此结果?我愿意接受任何不涉及创建专用类对象的方法,除非我必须这样做。

var lstApprovedButNotStartedWorkOrderDetailsItem = _workOrderDetailRepository.
    SearchFor(wod =>
        wod.ItemId == intItemId
    )               
    .OrderByDescending(wod => wod.WorkOrderHeader.OrderDetail.OrderHeader.RushOrderFlag)
    .Select(wod => new {
        wod.Id,
        wod.WorkOrderHeaderId,
        wod.ItemId,
        OriginalStatusId = wod.WorkOrderHeader.StatusId,
        NewStatusId = wod.WorkOrderHeader.StatusId,
        NeededQty = wod.EstimatedQuantity - wod.ActualQuantity,
        wod.Item.QtyAvailable
    })
    .ToList();

if (lstApprovedButNotStartedWorkOrderDetailsItem.Count <= 0) return ActionConfirmation<int>.CreateSuccessConfirmation("No open work orders for item", -1);

//loop through work order details in order, subtracting that line item's needs from the total available
for (int i = 0; i < lstApprovedButNotStartedWorkOrderDetailsItem.Count; i++)
{
    var wod = lstApprovedButNotStartedWorkOrderDetailsItem[i];
    //if wod 
    lstApprovedButNotStartedWorkOrderDetailsItem[i].NewStatusId = decTotalUnitsAvailable >= wod.NeededQty
        ? (int)WorkOrderStatus.Released
        : (int)WorkOrderStatus.InventoryHold;
}

2 个答案:

答案 0 :(得分:0)

您可以通过添加另一个具有与列表中相同属性的“匿名类型”,将 add 添加到现有的匿名类型列表中:

using System;
using System.Linq;

public class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello World");
        var list = (new [] { 1, 2, 3 })
            .Select(i => new { Value = i })
            .ToList();

        list.Add(new { Value = 4 });

        foreach (var i in list)
            Console.WriteLine(i);
    }
}

但是,匿名类型是不可变的。它们只是现有数据和计算的预测。因此,最好只为此创建一个自定义类型...不必太繁琐,只需创建一个新类型即可继承您正在使用的“旧”类型:

public class CustomWorkOrderDetailsItem : WorkOrderDetailsItem
{
    public int NewStatusId {get;set;}
}

答案 1 :(得分:-2)

必须将现有动态列表复制到ExpandoObjects的新动态列表中。不是最干净的,但是比创建专用的类(对我来说)更好:

var workOrderStatusList = new List<dynamic>();

//loop through work order details in order, subtracting that line item's needs from the total available
for (int i = 0; i < lstApprovedButNotStartedWorkOrderDetailsItem.Count; i++)
{
    //get wod instance
    var wod = lstApprovedButNotStartedWorkOrderDetailsItem[i];

    //Add new list item with updated status
    workOrderStatusList.Add(new ExpandoObject());
    workOrderStatusList[i].WorkOrderHeaderId = wod.WorkOrderHeaderId;
    workOrderStatusList[i].OriginalStatusId = wod.OriginalStatusId;
    workOrderStatusList[i].NewStatusId = decTotalUnitsAvailable >= wod.NeededQty
        ? (int)WorkOrderStatus.Released
        : (int)WorkOrderStatus.InventoryHold;

    //decrement allocated qty from available
    decTotalUnitsAvailable -= wod.NeededQty;
}