How to update an object in a List<> in C#
Using Linq to find the object you can do:
var obj = myList.FirstOrDefault(x => x.MyProperty == myValue);
if (obj != null) obj.OtherProperty = newValue;
But in this case you might want to save the List into a Dictionary and use this instead:
// ... define after getting the List/Enumerable/whatever
var dict = myList.ToDictionary(x => x.MyProperty);
// ... somewhere in code
MyObject found;
if (dict.TryGetValue(myValue, out found)) found.OtherProperty = newValue;
C# update object in list
No because item
is just a local variable, but you can use the indexer of the list:
int index = list.FindIndex(m => m.Id == viewModel.Id);
if(index >= 0)
list[index] = viewModel;
Update items in List<T> c#
Since your list contains a mutable type, all you need to do is get a reference to the specific item you want to update.
That can be done in a number of ways - using it's index, using the Find
method, or using linq are the first three that comes to mind.
Using index:
userData[0]?.Name = "CBA";
Using Find:
userData.Find(u => u.Name = "Abc")?.Name = "CBA";
Using linq (FirstOrDefault is not the only option):
userData.FirstOrDefault(u => u.Name = "Abc")?.Name = "CBA";
Note the use of null conditional operator (]?
and .?
) it prevents a null reference exception in case the item is not found.
Updating An object In A Collection C#
"How should I update the existingPepe"
There is no need to create a new instance of Person
, you can update the property Age
on the existing found instance directly. That mutates the actual instance itself. Doing that also means there is no need to swap the item in the List<Person>
.
// note that SingleOrDefault will throw an exception if there is more than one match
var foundPerson = people.SingleOrDefault(a => a.id ==someId);
if(foundPerson != null)
foundPerson.Age = 65;
// else person with that id does not exist in the list
If you want to have an exception thrown if there is no match then use Single instead.
var foundPerson = people.Single(a => a.id ==someId);
foundPerson.Age = 65;
Updating an object within a List of objects in C#
In the Update() function copycomp is referring to the object within
collection variable, so any changes made to the copycomp variable
doesn't need to assign it back to the collection like this :
The value of copycomp
is a reference to the object collection.subComponent1
, which is a List<SubComponent1>
. When you call a method and pass copycomp
as an argument (without the use of ref
) you actually pass a copy of this reference, this is the default behavior in C# and in many other high level programming languages. Hence you still have a reference to the original object and you can alter any value there. Specifically in your case you can remove items from the list, add other items, change the value of a property of an item etc.
If the above is that you want you don't need the ref
keyword. You should use the ref
keyword if you want to change the reference that copycomp
holds and then use the new reference for another purpose. In this case you could do any of the actions mentioned previously, which would result in the mutation of the object state that copycomp
points to and in addition to this you could change even the actual reference that copycomp
holds.
C# updating an object within a list
You are likely sharing the same object (reference) between 2 lists, so the price / name / or anything else will be reflected in both lists (as it's the same object).
You can think of a reference as a piece of paper which has the address of a physical location of stuff. When you are adding the reference to a list, or copy it. You are just coping the that piece of paper (the address). When you change a property, it looks up the actual physical location and it changes the stuff for everyone.
What you will need to do is clone your product. There are lots of ways to do this, some easier than others. However the most fundamental way is just copy the properties and state. Such that the internal state is the same.
var newProduk = new Produk()
{
Price = produk.Price,
Name = produk.Name,
...
// the rest of your state and properties
};
Tempuser._produk.Add(newProduk );
Update a List's object using Linq
You cannot replace the value in the list using LINQ, because LINQ is a projection of a collection.
You can get your item and then find it in the list using IndexOf
:
var item = Items.Single(i => i.Code == line.Code);
int index = Items.IndexOf(item);
Items[index] = new Item(); // replace the value
However, this approach is far from optimal in terms of algorithmic complexity, because it has to read through your list multiple times.
You can try to read more on Dictionary to find, add or replace items by key (in your case, Code
) efficiently.
Update an item in the list not working
Doing this:
var userToUpdate = userList.FirstOrDefault(r => r.IdUser == 3);
you get copy of reference that points to needed user. So, there are two different references pointing to this user: userToUpdate
and reference inside userList
.
When you assign newUser
to userToUpdate
you have one reference from list still pointing to the old user and you get reference userToUpdate
pointing to newUser
.
To update user you should do something like this:
var index = userList.FindIndex(r => r.IdUser == 3);
if (index != -1)
{
userList[index].Id = newUser.Id,
//set all other properties from newUser
}
OR
simpler way:
var index = userList.FindIndex(r => r.IdUser == 3);
if (index != -1)
{
userList[index] = newUser;
}
Update an Object by Matching with other Object Values depend on a Condition in C#
Thanks for those who tried to answer my question following solution worked for me
if (!string.IsNullOrWhiteSpace(caller) && !string.IsNullOrWhiteSpace(now) && !string.IsNullOrWhiteSpace(callee))
{
var recentChannel = activeChannels.FirstOrDefault(c => c.CallerExt == caller && c.CalleeExt == callee);
if (recentChannel != null)
recentChannel.ChannelName = now;
}
Related Topics
How to Generate Getters and Setters in Visual Studio
Using Enum and | as Dictionary Key
C# - Comparing Items Between 2 Lists
How to Set Datetimepicker to Month and Year Only Format
Controlling Datetime Parameter Formatting in Webapi 2
C# How to Split a List in Two Using Linq
How to Loop Through Each and Every Row, Put Value in Gridview Column Cells
Sorting String Values Without Using Any Method/Function
How to Asynchronously Wait for X Seconds and Execute Something Then
How to Round Up the Time to the Nearest X Minutes
How to Combine Values of Several Lists into One in C#
Launch an Application and Send It to Second Monitor
How to Delete Records Between Two Dates in Bulk
How to Convert a List to Ienumerable
C# Json Serialization of Dictionary into {Key:Value, ...} Instead of {Key:Key, Value:Value, ...}
How to Set Autoincrement Ids in Unit Test
Comparing Two Lists and Return Not Matching Items Results With Error