0

I have two lists (list) l1 & l2. i'm getting from outside the name of the list i want to use (let say l1).

how can i find requested list ?

do i need to use getMember method ?

thanks

2
  • It is very difficult to understand what you are asking. A code snippet will help.
    – Aliostad
    Commented Mar 28, 2011 at 22:07
  • 1
    It sounds like you are making this more complicated than it needs to be. Can you tell us more generally what you are trying to do?
    – tster
    Commented Mar 28, 2011 at 22:09

1 Answer 1

6

You can use reflection, but it's fairly expensive. Here's a question that outlines how to do that:

C# Reflection : Finding Attributes on a Member Field

Given that the list name is known at compile time, you could consider implementing a method that accepts the string name of the list and returns a reference to the appropriate list using a switch statement or if statement.

static IList FindList(string name)
{
  if (name == "l1") { return l1; }
  else if (name == "l2") { return l2; }
  else throw Exception("List " + name + " not found.");
}

That will be faster at runtime than using reflection but requires maintenance (if you have enough lists to warrant the effort, you could code generate that method).

3
  • You could also set this up as a Dictionary, keyed to possible values for name. Just saying; if you ever needed an l3, it would be a matter of simply adding it to the Dictionary, instead of also having to extend the switch statement.
    – KeithS
    Commented Mar 28, 2011 at 22:27
  • or he can use Dictionary<string, List<someobject>>, put both lists (or more) into this dictionary with name as key and then it's easy to get them out.
    – HABJAN
    Commented Mar 28, 2011 at 22:28
  • @KeithS you beat me for couple of seconds :-)
    – HABJAN
    Commented Mar 28, 2011 at 22:28

Not the answer you're looking for? Browse other questions tagged or ask your own question.