score:6
When your getting the item from a LIST its an reference type, if your updating anything to it then it will automatically change the values in LIST. Please check your self after updating...........
Item whichever your getting from
UserData.Where(s => s.ID == IDKey).ToList();
is an reference type.
score:7
You can get the index using the method
UserData.FindIndex(s => s.ID == IDKey)
It will return an int.
score:1
just fetch the object using SingleOrDefault
and make related changes; you do not need to add it to the list again; you are simply changing the same instance which is an element of the list.
var temp = UserData.SingleOrDefault(s => s.ID == IDKey);
// apply changes
temp.X = someValue;
score:2
As long as UserData
is reference type, the list only holds references to instances of that object. So you can change its properties without the need of remove/insert (and obviously do not need index of that object).
I also suggest you want to use Single
method (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
}
score:0
If I'm misunderstanding you then please correct me, but I think you're saying that you essentially want to iterate through the elements of a list, and if it matches a condition then you want to alter it in some way and add it to another list.
If that's the case, 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 which matches the following:
parameters: ElementType element, int index -- return: bool result
which allows it to either select or ignore the element based upon the boolean return. This allows us to submit a simple boolean expression, or a more complex function which has additional steps, as follows:
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: stackoverflow.com
Related Articles
- Insert an object in the list in C#
- Linq code to get the index of an object in an array from an object within a list
- How to bind and save an object containing a list of objects to database context in ASP.NET MVC with EF code first?
- Insert Anonymous object in a list of same anonymous type
- Create a tree structure in linq with a single list source with parent - child as strings of an object
- List or Array of String Contain specific word in Html Source Code
- Why is my code returning a list of the same object 4 times?
- c# Linq or code to extract groups from a single list of source data
- Create a list from two object lists with linq
- how to check if object already exists in a list
- LINQ: Select where object does not contain items from list
- Return list of specific property of object using linq
- Get index of object in a list using Linq
- Create a list of one object type from a list of another using Linq
- Mapping a list of object models onto another list using linq
- Linq select object from list depending on objects attribute
- Creating a list filled with new instances of an object
- Exclude items of one list in another with different object data types, LINQ?
- I am wondering about the state of connection and impact on code performance by 'yield' while iterating over data reader object
- Is an object still connected to a list after FirstOrDefault?
- How to get/find an object by property value in a list
- Generating the Shortest Regex Dynamically from a source List of Strings
- LINQ Where clause with Contains where the list has complex object
- How can I find object in List with Linq?
- Sort in list object
- C# : How to sort a list of object based on a list of string
- How to get an object from a list based upon IEqualityComparer<T>
- Take every 2nd object in list
- Linq query a List of objects containing a list of object
- Convert string array to custom object list using linq
- Native C# support for checking if an IEnumerable is sorted?
- How to filter data in a list using multiple conditions and LINQ?
- XML to SelectList using LINQ
- The Name 'insert name here' does not exist in the current context
- C# MVC ViewModel Returns Null - Postback
- How to filter a Linq Query from XML to IEnumerable of Objects
- Using LINQ to construct a list C#
- Using IEqualityComparer GetHashCode with a tolerance
- Pivot list data using LINQ
- LINQy way to check if any objects in a collection have the same property value
- LINQ to Entities generating incorrect SQL
- LINQ Query across complex parent/child/parent/child relationships
- EF: Select columns where any of them has value but not all of them
- LINQ version of SQL with left join and group by
- Get attribute value of parent node by Linq to XML
- C# Linq full outer join on repetitive values
- Why do I get a "key already added" error when using the key from a GroupBy in ToDictionary?
- LINQ sorting by number of appearances
- Issues with ListView here in C#
- Alternative Approach For generating list<key> from dict<string,string> where dict.value = "someValue"