2013-02-06 30 views
3

我有一個類對象列表UserData。我通過where方法得到這個列表中的對象在C列表中插入一個對象#

UserData.Where(s => s.ID == IDKey).ToList(); //ID is unique 

我想就在對象的一些變化,並在列表中的相同位置插入。但是,我沒有這個對象的索引。

任何想法如何做到這一點?

感謝

+4

您不必重新插入您直接在列表中工作也無妨... –

+0

不,我從這個列表中獲得一個對象。我不在名單上工作。我想刪除/插入或更新該對象 – Kiran

+0

是的,但您擁有的對象是對列表中的對象的引用,以便更新您找到的對象。你在哪裏自動更新列表中的一個...... –

回答

6

當你從一個LIST中獲取它的一個引用類型的項目時,如果你更新了任何東西,它會自動更改LIST中的值。請更新...........

項目無論您從

UserData.Where(s => s.ID == IDKey).ToList(); 

越來越是引用類型之後檢查你的自我。

+0

它的引用類型,而不是實例?發誓..這很容易。非常感謝 – Kiran

7

可以使用方法 UserData.FindIndex(s => s.ID == IDKey) 它會返回一個int拿到指標。

1

只是使用SingleOrDefault取物體並進行相關更改;你不需要再次將它添加到列表中;你只是簡單的改變列表中一個元素的實例。

var temp = UserData.SingleOrDefault(s => s.ID == IDKey); 
// apply changes 
temp.X = someValue; 
2

只要UserData是引用類型,該列表只保存對該對象實例的引用。所以你可以改變它的屬性而不需要刪除/插入(顯然不需要該對象的索引)。

我也建議你想用Single方法(而不是ToList()),只要id是唯一的。

public void ChangeUserName(List<UserData> users, int userId, string newName) 
{ 
    var user = users.Single(x=> x.UserId == userId); 
    user.Name = newName; // here you are changing the Name value of UserData objects, which is still part of the list 
} 
0

如果我誤解你,那麼請糾正我,但我覺得你說,你基本上是想通過一個列表中的元素進行迭代,並且如果它匹配條件,那麼你想以某種方式改變它,並將其添加到另一個列表。

如果是這種情況,請參閱下面的代碼,瞭解如何使用Where子句編寫匿名方法。 WHERE子句只是希望匿名函數或委託其匹配以下:

參數:元素的ElementType,INT指數 - 回報:布爾結果

它允許選擇或忽略基於布爾元素返回。這使我們能夠提出一個簡單的布爾表達式,或更復雜的功能,具有額外的步驟,如下所示:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace StackOverflow 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      int IDKey = 1; 
      List<SomeClass> UserData = new List<SomeClass>() 
      { 
       new SomeClass(), 
       new SomeClass(1), 
       new SomeClass(2) 
      }; 
      //This operation actually works by evaluating the condition provided and adding the 
      //object s if the bool returned is true, but we can do other things too 
      UserData.Where(s => s.ID == IDKey).ToList(); 
      //We can actually write an entire method inside the Where clause, like so: 
      List<SomeClass> filteredList = UserData.Where((s) => //Create a parameter for the func<SomeClass,bool> by using (varName) 
       { 
        bool theBooleanThatActuallyGetsReturnedInTheAboveVersion = 
         (s.ID == IDKey); 
        if (theBooleanThatActuallyGetsReturnedInTheAboveVersion) s.name = "Changed"; 
        return theBooleanThatActuallyGetsReturnedInTheAboveVersion; 
       } 
      ).ToList(); 

      foreach (SomeClass item in filteredList) 
      { 
       Console.WriteLine(item.name); 
      } 
     } 
    } 
    class SomeClass 
    { 
     public int ID { get; set; } 
     public string name { get; set; } 
     public SomeClass(int id = 0, string name = "defaultName") 
     { 
      this.ID = id; 
      this.name = name; 
     } 
    } 
}