将数据从一个集合复制到另一个集合C#

时间:2016-04-29 06:53:22

标签: c# linq collections

我想将数据从一个集合复制到另一个集合。我使用以下代码。

foreach (var x in invVM.invFreeItemsWithBatch)
            {
                invVM.invitemsWithBatch.Add(x);
            }

但这是错误的。我该如何纠正?

enter image description here

enter image description here

public ObservableCollection<InvFreeItemWithBatch> invFreeItemsWithBatch = new ObservableCollection<InvFreeItemWithBatch>();
    public ObservableCollection<InvFreeItemWithBatch> AddInvFreeItemsByBatch(int intitemID, string stritem, double dblqty, double dblamount, string struOM, bool blnfreeIssue,
        double dbluPrice, double dbldiscPerce, double dbldiscAmount, string strbatch, double dblBalanceForFreeqty)
    {
        invFreeItemsWithBatch.Add(new InvFreeItemWithBatch(intitemID, stritem, dblqty, dblamount, struOM, blnfreeIssue, dbluPrice, dbldiscPerce,
            dbldiscAmount, strbatch, dblBalanceForFreeqty));
        stritem = ""; struOM = "";
        return invFreeItemsWithBatch;
    }

    public ObservableCollection<InvItemWithBatch> invitemsWithBatch = new ObservableCollection<InvItemWithBatch>();
    public ObservableCollection<InvItemWithBatch> AddInvItemsByBatch(int intitemID, string stritem, double dblqty, double dblamount, string struOM, bool blnfreeIssue,
        double dbluPrice, double dbldiscPerce, double dbldiscAmount, string strbatch, double dblBalanceForFreeqty)
    {
        invitemsWithBatch.Add(new InvItemWithBatch(intitemID, stritem, dblqty, dblamount, struOM, blnfreeIssue, dbluPrice, dbldiscPerce,
            dbldiscAmount, strbatch, dblBalanceForFreeqty));
        stritem = ""; struOM = "";
        return invitemsWithBatch;
    }

1 个答案:

答案 0 :(得分:0)

invFreeItemsWithBatch 包含与 invitemsWithBatch 不同的元素类型。

一个列表包含 InvItemWithBatch 元素的类型,另一个包含 InvFreeItemWithBatch。

如果您愿意,可以在foreach中创建新元素。

foreach (var x in invVM.invFreeItemsWithBatch)
{
    var newItem = new InvFreeItemWithBatch();
    // set the values of newItem to match the values of x
    // ...
    invVM.invitemsWithBatch.Add(newItem);
}

还考虑将 InvItemWithBatch 作为 InvFreeItemWithBatch 的基类:

class InvFreeItemWithBatch : InvItemWithBatch

那样你可以输入

foreach (var x in invVM.invFreeItemsWithBatch)
        {
            invVM.invitemsWithBatch.Add(x);
        }

但你必须考虑,这两个列表对x具有相同的参考。