Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search list of objects based on object variable

Tags:

c#

list

search

I have a list of objects. These objects have three variables, ID, Name, & value. There can be a lot of objects in this list, and I need to find one based on the ID or Name, and change the value. Example

class objec
{
    public string Name;
    public int UID;
    public string value;
}
List<objec> TextPool = new List<objec>();

How would I find the one entry in TextPool that had the Name of 'test' and change its value to 'Value'. The real program has many more search options, and values that need changing, so I couldn't just use a Dictionary (though Name and UID or unique identifiers). Any help would be great

like image 293
Ben Avatar asked Jul 01 '10 00:07

Ben


People also ask

How do you check if a list of object contains a value?

contains() methodReturns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o. equals(e)).

How do you search for a specific object in a list Python?

To find an element in the list, use the Python list index() method, The index() is an inbuilt Python method that searches for an item in the list and returns its index. The index() method finds the given element in the list and returns its position.


2 Answers

You could use LINQ to find it, then change the element directly:

var item = TextPool.FirstOrDefault(o => o.Name == "test");
if (item != null)
       item.value = "Value";

If you wanted to change all elements that match, you could, potentially, even do:

TextPool.Where(o => o.Name == "test").ToList().ForEach(o => o.value = "Value");

However, I personally would rather split it up, as I feel the second option is less maintainable (doing operations which cause side effects directly on the query result "smells" to me)...

like image 200
Reed Copsey Avatar answered Oct 31 '22 11:10

Reed Copsey


var find = TextPool.FirstOrDefault(x => x.Name == "test");
if (find != null)
{
    find.Name = "Value";
}
like image 20
Jamie Ide Avatar answered Oct 31 '22 12:10

Jamie Ide