【问题标题】:Access an item of Array of class using a member variable in place of index in C#使用成员变量代替 C# 中的索引访问类的数组项
【发布时间】:2012-03-29 17:22:11
【问题描述】:

假设我有一个类似的课程

class ABC
{
    int ID;
    public string Name;
    public ABC(int i, string str) { ID = i; Name = str; }
}

并声明一个ABC类的数组。 假设我还使用 new 关键字初始化了每个元素。 现在我想使用它的成员 ID 而不是基于 0 的索引来访问类的元素。如果需要,公开 ID。

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ABC[] a = new ABC[3];
        a[0] = new ABC(100, "First");
        a[1] = new ABC(101, "Second");
        a[2] = new ABC(102, "Third");

        ABC newobj = a[100]; // where 100 is ID of class ABC
    }
}

class ABC
{
    int ID;
    string Name;
    public ABC(int i, string str)
    {
         ID = i;
         Name = str;
    }
}

【问题讨论】:

  • 那你为什么不把它们放到Dictionary<int, ABC>呢?
  • 你能给我一个示例代码吗?我不知道如何在 .NET 中使用字典
  • 我不能,但 Google 和 MSDN 可以。
  • 请投票支持我的问题。我需要一些分数来投票给答案。

标签: c# .net arrays oop


【解决方案1】:

您可以使用LINQ 来获取正确的对象:

ABC newobj = a.Where(abc => abc.ID == 100).FirstOrDefault();

如果没有匹配的 ID,则返回 null

正如@Xanatos 所建议的,您也可以使用这个更简洁的版本:

ABC newobj = a.FirstOrDefault(abc => abc.ID == 100);

正如@Jon 所建议的,最好使用Dictionary<int, ABC> 来存储您的ABC 实例。与总是迭代 Collection 来查找匹配 ID 相比,它提供了更好的性能。但是key必须是唯一的,不能添加两个ID相同的ABC实例:

var a = new Dictionary<int, ABC>();
a.Add(100, new ABC(100, "First"));
a.Add(101, new ABC(101, "Second"));
a.Add(102, new ABC(102, "Third"));

你可以这样访问它:

ABC newobj = a[100];

【讨论】:

  • 这也可以工作:ABC newObj = a.Single(abc => abc.ID == 100);但是,我们的方法现在都不行了,因为这些字段是私有的......:D
  • 工作正常.. 感谢您的及时响应.. 但我想以同样的方式执行此操作,就像我们可以访问 cookie 名称为 Request.Cookies["CookieName"].Value 的 cookie。这怎么可能..??
  • 或更简洁的ABC newobj = a.FirstOrDefault(abc =&gt; abc.ID == 100);
  • @ShashwatIndia:我刚刚添加了字典方法。
  • Lookup&lt;TKey, TElement&gt;(非唯一键)或Dictionary&lt;TKey, TValue&gt;(唯一键,正如其他人已经写过的)将允许您通过索引器 (abc[100]) 进行访问。您还可以使用索引器实现您自己的数据结构(请参阅msdn.microsoft.com/en-us/library/6x16t2tx.aspx),但我认为现有类之一非常适合。
【解决方案2】:

这是使用Dictionary (MSDN) 的代码:

//instantiate it: key is of type int, value is of type string
var dict = new Dictionary<int, string>();
//add a few items...
dict.Add(100, "First");
dict.Add(101, "Second");

//get item with key '100'
var first = dict[100];

希望这会有所帮助!

【讨论】:

  • 请投票支持我的问题。我需要一些分数来投票给答案。
【解决方案3】:

在 C# 中无法在标准数组上重载索引器。如果你必须走索引器路线,我建议使用 Dictionary 或提供它自己的索引器的 List 类。

class ABCCollection : List<ABC>
{
  public ABC this[int id]
  {
    get { return this.Where(abc => abc.ID == id).FirstOrDefault(); }
  }
}

然后你调用 use ABCCollection[100] 来访问你的项目。

【讨论】:

  • 我喜欢这种方法.. 请告诉我这种方法比 Dictionary.. 有什么缺点吗??任何性能问题..??
  • 请投票支持我的问题。我需要一些分数来投票给答案。
  • 我不能以我的方式覆盖 Add() 函数吗??
  • 在这种情况下不要从 List 继承,而是从 CollectionBase 继承并实现自己的 Add 方法。
【解决方案4】:

您可以简单地使用 LINQ 查询来解决问题:

 var newobj = (from data in a
               where data.ID ==100
               select data).Cast<ABC>();

【讨论】:

  • 请投票支持我的问题。我需要一些分数来投票给答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多