Insert object into list in c #
I have a list of class objects UserData
. I am getting an object from this list using the methodwhere
UserData.Where(s => s.ID == IDKey).ToList(); //ID is unique
I would like to make some changes to the object and paste at the same place in the list. However, I do not have an index of this object.
Any idea how to do this?
thank
source to share
While it UserData
is a reference type, the list contains only references to instances of that object. This way you can change your properties without needing to delete / insert (and obviously don't need the index of that object).
I also suggest that you use the method Single
(instead of ToList()
) as long as the id is unique.
Example
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
}
source to share
If I don't understand you, then please correct me, but I think you are saying that you essentially want to iterate over the elements of the list, and if that matches the condition, then you want to modify it in some way and add it to another list ...
If so, then please see the code below to see how to write an anonymous method using the Where clause. The Where clause just wants an anonymous function or delegate that matches the following:
: ElementType, int index - return: bool result
which allows you to either select or ignore an item based on a boolean return. This allows us to represent a simple boolean expression or a more complex function with additional steps:
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;
}
}
}
source to share