简体   繁体   中英

How can I get the name of a List<string>

I am working on a C# WPF application. Here is a sample of my code:

private static List<string> a = new List<string>();
private static List<string> b = new List<string>();
private static List<string> c = new List<string>();

Then I have another list like this:

private static List<List<string>> alphabet = new List<List<string>>() { a, b, c };

I need to access a, b, or c as a string. so I need to get the name of the items inside alphabet list. It seems that list does not have any name property.

What you're asking for is impossible. a , b and c are local variables names that are parsed by the compiler, but are not, in fact, kept throughout the process. The final, compiled DLL or EXE does not contain the names of these variables, just references to memory locations. There's no way to get these names at runtime - they're not part of the data structure, nor are they available as metadata.

It seems that what you're after is being able to access a specific list by name, but a) a List doesn't have a name, and b) a List, the outer list, isn't a good data structure to access objects by name. Unlike languages like PHP who use associative arrays by default, C# is stricter with its data structures - a List<T> is an index-accessible array-backed list, not an associative array.

If your intention is to access an object by name, you'll have to use a data structure that's designed for it - in this case, a Dictionary<string, List<string>> . This will allow you to set a name as a key to access an object:

private List<string> a = new List<string>();
private List<string> b = new List<string>();
private List<string> c = new List<string>();

private Dictionary<string, List<string>> lists = new Dictionary<string, List<string>>();  
lists.Add("a", a);
lists.Add("b", b);
lists.Add("q", c); // note that the key isn't related to the variable name.

You can then access a specific list by name through the Dictionary's indexer property:

var cList = lists["q"];

Alternate interpretation

Since your question isn't entirely clear, it's possible, based on one comment, that you simply want to extend the List<string> class to also carry a name, for some reason - perhaps to store a SQL table name associated with it, even though that's a pretty bad design that couples your code to a specific database structure.

This can be achieved by subclassing List<string> and adding a new property:

public class NamedList<T> : List<T>
{
     public NamedList(string name)
     {
          Name = name;
     }
     public string Name {get;set;}
}

Now, instead of creating a List<string> , you'll create a NamedList:

var a = new NamedList<string>("a");
var q = new NAmedList<string>("c");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM