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

本文关键字:插入 一个对象 列表 | 更新日期: 2023-09-27 17:58:11

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

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

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

知道怎么做吗?

感谢

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

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

当您从LIST中获取该项时,如果您对其进行了任何更新,它将自动更改LIST中的值。更新后请自我检查。。。。。。。。。。。

从获得的物品

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

是引用类型。

只要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
}

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

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

如果我误解了你,请纠正我,但我认为你的意思是,你本质上想遍历列表的元素,如果它匹配一个条件,那么你想以某种方式更改它,并将其添加到另一个列表中。

如果是这种情况,请参阅下面的代码,了解如何使用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;
        }
    }
}