使用LINQ更新集合中的一个对象

时间:2017-02-08 09:50:30

标签: c# linq

我在这个对象中有对象和集合。

myObject.myCollection.Where(a => a.Id == Id).FirstOrDefault() = newMyCollection;

不幸的是,这不起作用

如果我改变单个元素,那么工作。例如:

myObject.myCollection.Where(a => a.Id == Id).FirstOrDefault().Id = newMyCollection.Id;

如何更新所有对象?谢谢你的帮助

我可以这样做:

myObject.myCollection.Remove(objectOfMyCollection);
myObject.MyCollection.Add(myNewCollection);

但是:如果我的objectOfMyCollection是第一个,那么我的新对象就是最后一个。

5 个答案:

答案 0 :(得分:1)

您只需查询列表并对其进行迭代:

objectStore.openCursor()

答案 1 :(得分:1)

试试这个

var customListItem2 = myObject.myCollection.Where(a => a.Id == Id).FirstOrDefault();
var index = myObject.myCollection.IndexOf(customListItem2);

if(index != -1)
    myObject.myCollection[index] = newCustomListItem;

答案 2 :(得分:0)

您必须替换列表中的基础引用,这是LINQ无法实现的(专为查询而非更新对象而设计)。

要使用列表使用旧学校[4, 16, 36, 64] [1, 9, 25, 49] - 循环:

for

此处需要使用for(int i = 0; i < myList.Count; i++) { if(myList[i].Id == Id) { myList[i] = newElement; break; } } - 而不是for,因为您重新引用列表中的实例,而使用后者无法实现。

另一种方法是创建列表的临时副本,在那里获取匹配元素,并将其作为列表中的索引,并替换原始列表中该索引处的元素:

foreach

答案 3 :(得分:0)

要仅更改第一个索引,您可以执行以下操作:

myObject.myCollection.Where(a => a.Id == Id).FirstOrDefault(a => { a.Id = newMyCollection.Id; return true; });

用简单的英语做:

- From myCollection get items Where item's Id is equal to Id

- From selected values get FirstItem and set it's Id to the new one

- Do not check the rest

甚至可以简化:

myObject.myCollection.FirstOrDefault(a => { if(a.Id == Id) { a.Id = newMyCollection.Id; return true; } return false; });

答案 4 :(得分:0)

如果要复制SQL a = "Apple Banana oranges grapes. free free free phones. deals deals time.black white grey" sentences = a.split(/\./) # Split on `.` # Initialize variables free_count = 0 deal_count = 0 no_match = [] matches = [] sentences.each do |i| # Go through each sentence if (m = i.scan(/free/)) && m.any? # Try matching "free", and check if there is any matches matches << i # Add match to matches array free_count += m.length # Count up amounts of `free` spotted. elsif (m = i.scan(/deals/)) && m.any? # Try matching "deals", and check if there is any matches matches << i # Add match to matches array deal_count += m.length # Count up amounts of `deals` spotted. else no_match << i # Count up for nothing spotted end end p free_count #=> 3 p deal_count #=> 2 p no_match #=> ["Apple Banana oranges grapes", "black white grey"] p matches #=> [" free free free phones", " deals deals time"] 并更新一个或多个对象,则可以按以下方式使用LINQ,这次使用UPDATE with JOIN派生的对象。但是您可以使用CollectionBase

List<T>

有点骇人听闻,但其行为类似于SQL,并且不会使集合发生变异。是的,它会创建仅包含原始收集项目参考的轻型对象。

相关问题