如果未找到,则从另一个列表更新列表然后插入

时间:2015-07-23 06:21:17

标签: c# linq list

在我的应用程序中,我必须检查MyListDeepCopy是否为empty,如果是,我将复制原始列表:

MyListDeepCopy = new List<Storage>(Storage.MyStorage);

现在填充了MyListDeepCopy我想每次检查原始list时进行检查。如果将item添加到原始list,我必须insert新项目MyListDeepCopy,否则update

有人能告诉我一个例子它是如何完成的吗? (可能使用LINQ)

编辑:我通过这样做解决了这个问题:(插入)

if (MyListDeepCopy.Count() == 0)
    {
        MyListDeepCopy  = new List<Storage>(Storage.MyStorage);
    }
    else 
    {
        var ItemOnDeepList = Storage.MyStorage.Where(x => !MyListDeepCopy.Any(y => x.ItemID == y.ItemID));
        if(ItemOnDeepList != null)
        {
            foreach (var item in ItemOnDeepList) 
            {
                MyListDeepCopy.Add(item);
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

请查看以下示例。在此我正在更新列表,如果找到项目,则添加项目。

class Program
{
    static void Main(string[] args)
    {
        var originalList = CreateOriginalList();// Original List
        List<Item> MyListDeepCopy = new List<Item>();// Empty List

        // Copy Original List to MyListDeepCopy if later is empty.
        if (MyListDeepCopy.Count() == 0)
            MyListDeepCopy = (List<Item>)originalList;

        {
            /* DELETE IF FOUND */
            int dItemId = 11;

            // Update originalList
            originalList.RemoveAll(d => d.ItemId == dItemId);
            // Update same in MyListDeepCopy
            MyListDeepCopy.RemoveAll(d => d.ItemId == dItemId);
        }


        {
            /* ADD IF NOT EXIST ELSE UPDATE */
            int aItemId = 17;
            double aItemPrice = 1200;

            // ADD to originalList
            originalList.Add(new Item { ItemId = aItemId, ItemPrice = aItemPrice });

            // Update 
            if (MyListDeepCopy.Exists(a => a.ItemId == aItemId))
                (MyListDeepCopy.FirstOrDefault(o => o.ItemId == aItemId)).ItemPrice = aItemPrice;
            else
                MyListDeepCopy.Add(new Item { ItemId = aItemId, ItemPrice = aItemPrice });
        }          
    }

    private static List<Item> CreateOriginalList()
    {
        return new List<Item> 
        {
            new Item{ ItemId = 11, ItemPrice = 100},
            new Item{ ItemId = 12, ItemPrice = 1000},
            new Item{ ItemId = 13, ItemPrice = 1050},
            new Item{ ItemId = 14, ItemPrice = 600},
            new Item{ ItemId = 15, ItemPrice = 900}
        };            
    }
}

public class Item
{
    public int ItemId{get; set;}
    public double ItemPrice { get; set; }

    public override string ToString()
    {
        return string.Format("{0}  :  {1}", ItemId, ItemPrice);
    }
}