JL.
JL.

Reputation: 81262

Getting an item in a list

I have the following list item

public List<Configuration> Configurations
{
    get;
    set;
}

 public class Configuration
  {
    public string Name
     {
       get;
       set;
     }
    public string Value
      {
       get;
       set;
     }
 }

How can I pull an item in configuration where name = value?

For example: lets say I have 100 configuration objects in that list.

How can I get : Configurations.name["myConfig"]

Something like that?

UPDATE: Solution for .net v2 please

Upvotes: 11

Views: 95536

Answers (5)

Jason Evans
Jason Evans

Reputation: 29186

Here's one way you could use:

static void Main(string[] args)
        {
            Configuration c = new Configuration();
            Configuration d = new Configuration();
            Configuration e = new Configuration();

            d.Name = "Test";
            e.Name = "Test 23";

            c.Configurations = new List<Configuration>();

            c.Configurations.Add(d);
            c.Configurations.Add(e);

            Configuration t = c.Configurations.Find(g => g.Name == "Test");
        }

Upvotes: 0

Greg Beech
Greg Beech

Reputation: 136577

Using the List<T>.Find method in C# 3.0:

var config = Configurations.Find(item => item.Name == "myConfig");

In C# 2.0 / .NET 2.0 you can use something like the following (syntax could be slightly off as I haven't written delegates in this way in quite a long time...):

Configuration config = Configurations.Find(
    delegate(Configuration item) { return item.Name == "myConfig"; });

Upvotes: 25

Amber
Amber

Reputation: 526543

It seems like what you really want is a Dictionary (http://msdn.microsoft.com/en-us/library/xfhwa508.aspx).

Dictionaries are specifically designed to map key-value pairs and will give you much better performance for lookups than a List would.

Upvotes: 6

Dykam
Dykam

Reputation: 10290

Consider using a Dictionary, but if not:


You question wasn't fully clear to me, one of both should be your answer.

using Linq:

var selected = Configurations.Where(conf => conf.Name == "Value");

or

var selected = Configurations.Where(conf => conf.Name == conf.Value);

If you want it in a list:

List<Configuration> selected = Configurations
    .Where(conf => conf.Name == "Value").ToList();

or

List<Configuration> selected = Configurations
    .Where(conf => conf.Name == conf.Value).ToList();

Upvotes: 3

weiqure
weiqure

Reputation: 3235

Try List(T).Find (C# 3.0):

string value = Configurations.Find(config => config.Name == "myConfig").Value;

Upvotes: 0

Related Questions