我有一个名为CandidateListOfMyObjects的对象MyObjects列表和另一个名为InitialListOfMyObjects的列表。我正在编写一个方法,使用linq更新,删除或添加MyObjects实例到列表中?
这在循环中起作用:
MyObject ThisObject = new MyObject(); //MyObject has a field call ObjectID
for (int index = 0; index < ListOfMyObjects.Count; index++)
{
ThisObject = null;
ThisObject = ListOfMyObjects[index];
if (condition)
{
add ThisObject to InitialListOfMyObjects
}
if (condition)
{
replace the MyObject with ID ThisObject.ID in the InitialListOfMyObjects with ThisObject
}
if (condition)
{
delete the ThisObject with ID ThisObject.ID from the InitialListOfMyObjects
}
}
现在,我正在循环遍历InitialListOfMyObjects,但是当我查看我的代码时,我正在循环中进行循环,所以我确信这不是最好的方法。
感谢您的建议。
答案 0 :(得分:1)
使用linq
将数据添加到列表中 public void insertintolist()
{
var accountService = new AccountServicetest();
var storethread = new Thread();
storethread.TrdTopic = "JavaScript";
storethread.EmailID = "nived@gmail.com";
storethread.Name = "nived";
storethread.Topic = "Function";
storethread.Message = "what is a functio ";
storethread.Posts = 0;
storethread.Views = 0;
accountService.StoreThread(storethread);
}
public void StoreThread(Thread model)
{
if (model != null)
{
model.TrdTopicID = 4;
accountcontrollertest.storethread.Add(model);
}
}
答案 1 :(得分:0)
您可以创建自己的扩展方法。将此方法放在公共静态类中:
public static void ForEach<T>(this IEnumerable<T> values, Action<T> action)
{
foreach (var value in values)
action(value);
}
它使您能够对LINQ样式中的可枚举元素执行操作。
articles
.Where(a => a.Price < 100.0)
.ForEach(a => { a.Price *= 1.2; a.Updated = true; });
答案 2 :(得分:0)
我不确定你的condition
是什么样的,但我认为只是用更新的列表替换原始列表是不够的。这是我在两个列表之间同步的Linq版本。
//replace original with synchronized list
original = from updatedPair in updated
join originalPair in original
//group join the updated to the original:
//all updates will be included,
//but only those originals with a matching update
//(deletes items not in the updated list automatically)
on updatedPair.Key equals originalPair.Key
into originalsForUpdate
//added items will have a null originalForUpdate
let originalForUpdate = originalsForUpdate.DefaultIfEmpty().Single()
where !ConditionForDelete(updatedPair, originalForUpdate)
select new MyObjectThingy
{ updatedPair.Key,
ConditionForUpdate(originalForUpdate,updatedPair) ?
updatedPair.Value :
originalForUpdate.Value
}.ToList();
请注意,虽然这允许添加或更新条件,但它在删除时只有有限的条件 - 只在原始列表中但不在更新列表中的任何内容都不在结果集中。要解决此问题,您可以在最后致电Union(original.Where(item => !updated.Any(updItem => updItem.Key == item.Key) && ConditionForUndoingDelete(item)))
之前致电ToList
。