Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting an item in a list

Tags:

c#

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

like image 560
JL. Avatar asked Aug 01 '09 11:08

JL.


People also ask

What is an item in a list Python?

A list is a data structure in Python that is a mutable, or changeable, ordered sequence of elements. Each element or value that is inside of a list is called an item. Just as strings are defined as characters between quotes, lists are defined by having values between square brackets [ ] .

How do you get the number of an item in a list?

The most straightforward way to get the number of elements in a list is to use the Python built-in function len() . As the name function suggests, len() returns the length of the list, regardless of the types of elements in it.

How do you access elements in a list?

The syntax for accessing the elements of a list is the same as the syntax for accessing the characters of a string. We use the index operator ( [] – not to be confused with an empty list). The expression inside the brackets specifies the index.


2 Answers

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"; });
like image 111
Greg Beech Avatar answered Oct 22 '22 15:10

Greg Beech


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.

like image 32
Amber Avatar answered Oct 22 '22 15:10

Amber