在C#中将对象插入列表

3

我有一个类对象UserData的列表。我通过where方法从这个列表中获取一个对象。

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

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

有什么想法吗?

谢谢


4
你不需要重新插入它,因为你直接在列表中进行操作。 - Paul Sullivan
不,我从这个列表中获取一个对象。我并没有直接操作这个列表。我想要移除/插入或更新那个对象。 - Kiran
是的,但你拥有的对象是列表中的一个引用,因此通过更新在 .Where 中找到的对象,你自动更新了列表中的一个对象... - Paul Sullivan
UserData 包含哪些类型?它们是 class 还是 struct - Ilya Ivanov
@IlyaIvanov 这是一个类的列表。 - Kiran
5个回答

7

您可以使用以下方法获取索引:

UserData.FindIndex(s => s.ID == IDKey)

它将返回一个整数。


6

当您从列表中获取项目时,它是引用类型,如果您更新其中的任何内容,则它将自动更改列表中的值。请在更新后自行检查...........

无论哪个项目您正在获取

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

是一种引用类型。


它是一个引用类型,而不是一个实例?哇..这使它变得容易。非常感谢。 - Kiran

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
}

1

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

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

0

如果我误解了您的意思,请纠正我,但我认为您的意思是您想要遍历列表的元素,如果符合某个条件,则想要对其进行修改并添加到另一个列表中。

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

参数:ElementType element,int index--返回值:bool result

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接