在C#中的列表中插入一个对象

时间:2013-02-06 12:41:22

标签: c# linq

我有一个类对象列表UserData。我通过where方法

从此列表中获取了一个对象
UserData.Where(s => s.ID == IDKey).ToList(); //ID is unique

我想在对象中进行一些更改并插入列表中的相同位置。但是,我没有这个对象的索引。

知道该怎么做吗?

由于

5 个答案:

答案 0 :(得分:7)

您可以使用该方法获取索引 UserData.FindIndex(s => s.ID == IDKey) 它将返回一个int。

答案 1 :(得分:6)

当您从LIST获取项目时它是一个引用类型,如果您更新任何内容,那么它将自动更改LIST中的值。更新后请检查自己...........

您从

获取的项目
UserData.Where(s => s.ID == IDKey).ToList(); 

是一种参考类型。

答案 2 :(得分: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
}

答案 3 :(得分:1)

使用SingleOrDefault获取对象并进行相关更改;你不需要再次将它添加到列表中;您只是更改同一个实例,它是列表的一个元素。

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

答案 4 :(得分:0)

如果我误解了你,那么请纠正我,但我认为你说你基本上想要遍历列表中的元素,如果它符合某个条件,那么你想要改变它以某种方式将其添加到另一个列表中。

如果是这种情况,请参阅下面的代码,了解如何使用Where子句编写匿名方法。 Where子句只需要一个与以下内容匹配的匿名函数或委托:

参数:ElementType元素,int索引 - 返回:bool结果

允许它根据布尔返回选择或忽略元素。这允许我们提交一个简单的布尔表达式,或者一个更复杂的函数,它具有额外的步骤,如下所示:

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;
        }
    }
}