tags:

views:

64

answers:

4

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,
Thanks,
Max

+6  A: 

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)...

Reed Copsey
+1. Slow typer is slow.
womp
Calling .ToList() just to use the ForEach extension smells more to me.
Joel Coehoorn
@Joel: The ForEach isn't an extension ;) But yeah, the second case smells to me, too - but I figured I'd list it as an option, too...
Reed Copsey
@Joel: Any reason you removed my explicit declaration, and put in var? "objec" was the OP's class name, not a typo...
Reed Copsey
@Reed: Another option for your second example would be to do `TextPool.FindAll(o => o.Name == "test").ForEach(o => o.value = "Value");` instead.
LukeH
@Reed - it _looked_ like a typo, and so I changed it to remove any confusion later. If you want to put it back, I don't care.
Joel Coehoorn
A: 

Sounds like a job for LINQ!

var matchedObject =
   from t in TextPool
   where t.UName == "test"
   select t;

This is assuming your search is defined in code. If your code is driven by the UI, you may simply need to do a linear iteration. To search all possible attributes, without indexing, it isn't going to get any faster.

[ Edit: Was beaten to the punch, but leaving this up as an example of a different syntax, plus a link ]

Nicholas M T Elliott
A: 
List<objec> TextPool = new List<objec>();
objec found = TextPool.FirstOrDefault(item => item.Name == "test");
if (found != null) found.value = "Value";

If you are going to perform many lookups, you could cache the results in multiple Dictionary<> instances (or Lookup<> instance if keys are not unique).

Jaroslav Jandek
A: 
var find = TextPool.FirstOrDefault(x => x.Name == "test");
if (find != null)
{
    find.Name = "Value";
}
Jamie Ide