Вот код, который добавит элемент к dpIndexList
, если там нет элемента с таким «API», или обновит элемент в этом списке, если существует элемент с таким «API»:
foreach (var item in items)
{
// Check if the item with such API already exists in dpIndexList
var foundItem = dpIndexList.FirstOrDefault(dpItem => dpItem.API == item.API);
if (foundItem != null)
{
// Exists. Update the item in dpIndexList
foundItem.File = item.File;
foundItem.Location = item.Location;
}
else
{
// Doesn't exist. Adding to dpIndexList
dpIndexList.Add(item);
}
}
Для тестирования локально я использовал следующие фиктивные списки, и это сработало:
var dpIndexList = new List<DPIndex>()
{
new DPIndex
{
API = "1",
File = "File_1_ORIG",
Location = 1111
},
new DPIndex
{
API = "2",
File = "File_2_ORIG",
Location = 2222
},
};
var items = new List<DPIndex>()
{
// Item, which exists in dpIndexList (should update the original)
new DPIndex
{
API = "2",
File = "File_2_UPDATE",
Location = 3333
},
// New item, which doesn't exist in dpIndexList (should be added)
new DPIndex
{
API = "3",
File = "File_3_NEW",
Location = 3333,
},
// Item, which should UPDATE the one above (should update that one)
new DPIndex
{
API = "3",
File = "File_3_UPDATED",
Location = 3333
},
};
PS Не забудьте добавить using System.Linq;
в начало файла.