代码之家  ›  专栏  ›  技术社区  ›  user195488

存储数据字段集合并通过标识符检索

  •  0
  • user195488  · 技术社区  · 15 年前

    在C#中,如何存储一组值,以便在以后检索特定值时,可以执行以下操作:

    count=myCollection[“Area1”].AreaCount;

    我想将多个属性存储到一个“键”。上课就是答案吗?

    3 回复  |  直到 15 年前
        1
  •  1
  •   AllenG    15 年前

    编辑
    根据你的评论,似乎你想要一本字典(正如已经建议的那样),在那里你的对象保存你所有的“值”

    例如:

    public class MyClass
    {
       public int AreaCount;
       public string foo;
       public bool bar;
    }
    
    //Create dictionary to hold, and a loop to make, objects:
    Dictionary<string, MyClass> myDict = new Dictionary<string, MyClass>();
    while(condition)
    { 
       string name = getName(); //To generate the string keys you want
       MyClass mC = new MyClass();
       myDict.Add(name, mC);
    }
    
    //pull out yours and modify AreaCount
    myDict["Area1"].Value.AreaCount = 50;
    

    string “Name”到您的类(我使用字段作为示例,您可能会使用属性)并使用Linq:

    //Now we have a list just of your class (assume we've already got it)
    myClass instanceToChange = (from items in myList
                              where Name == "Area1"
                              select item).FirstOrDefault();
    
    myClass.AreaCount = 50;
    

    这有帮助吗?

    原始响应

    给定一个需要从中获取特定对象的对象列表,通常有4种方法-取决于您的特定需要。

    List<T> 只有当您的对象已经支持某种类型的搜索(如String.Contains())时,才能真正做到这一点。

    A SortedList 使用IComparer比较和排序键值,并以此方式排列列表。

    A Dictionary 存储键和值,以便 KeyValuePair

    A HashTable 在键必须实现的地方使用键和值 GetHashCode() ObjectEquals

        2
  •  2
  •   SLaks    15 年前

    你在找 Dictionary<string, YourClass> class . (在哪里? YourClass 有一个 AreaCount 财产)

        3
  •  0
  •   Damian Leszczyński - Vash    15 年前

    此功能由提供 indexers