【问题标题】:Issues trying to get Index Location in IList尝试在 IList 中获取索引位置的问题
【发布时间】:2012-03-22 19:49:23
【问题描述】:
class IList2
{
    static void Main(string[] args)
    {

        Locations test = new Locations();
        Location loc = new Location();
        string sSite = "test";
        test.Add(sSite);
        string site = loc.Site; 
        Location finding = test.Where(i => i.Site == site).FirstOrDefault();
        int index = finding == null ? -1 : test.IndexOf(finding); 
    }
}

public class Location
{
    public Location()
    {

    }
    private string _site = string.Empty;
    public string Site
    {
        get { return _site; }
        set { _site = value; }
    }
 }

 public class Locations : IList<Location>
 {
    List<Location> _locs = new List<Location>();

    public Locations() { }

    public int IndexOf(Location item)
    {

        return _locs.IndexOf(item);

    }
    //then the rest of the interface members implemented here in IList
    public void Add(string sSite)
    {
        Location loc = new Location();
        loc.Site = sSite;

        _locs.Add(loc);
    }
  }

  IEnumerator<Location> IEnumerable<Location>.GetEnumerator()
    {
        return _locs.GetEnumerator();
    }

我在这篇文章中得到了一些帮助:Trying to call int IList<Location>.IndexOf(Location item) method

我试图让这个工作,但我似乎总是得到 -1 作为索引号。我知道字符串 site = loc.Site; 在意识到这一点后是空的,所以我现在不知道如何从 IList 中获取索引。

为了弄清楚我想要完成的工作,我想学习如何使用 IList 接口成员,我从 IndexOf 接口开始。

IList 不仅包含“sSite”,但出于示例目的,我只是将列表简化为“sSite”。

所以在学习的过程中,我遇到了这个障碍,并且盯着代码看了几天(是的,我会休息一下,看看其他的东西,以免让自己筋疲力尽)。

所以主要问题是我不断得到 index = -1。

【问题讨论】:

  • 那么你期望哪个索引给出空列表?!
  • 这真的让你想做什么感到困惑。在 Main 函数的第 3 行,loc 是什么?我没有看到它在该方法的任何地方声明。
  • 感谢尼克指出这一点,我补充了。

标签: c# .net c#-4.0


【解决方案1】:

我不清楚你的意图是什么,但在代码中 sn-p "loc" 从未使用过,因为你在 "Add" 方法中创建了一个新的Location 而 "site" 是(因为你'已经注意到)始终为空,但在“添加”方法中,您传入一个值并将其设置在新创建的实例上,因此除非您将 string.Empty 作为值传递,否则比较 i.Site == site 将始终为 false。如果您删除它们并重写为:

Locations test = new Locations();
string sSite = "test";
test.Add(sSite);
Location finding = test.Where(i => i.Site == sSite).FirstOrDefault();
int index = test.IndexOf(finding); 

然后这将返回0 作为索引。

【讨论】:

  • 感谢您发现这个错误。好的,我按照您之前的建议做了,但由于某种原因我没有听懂。谢谢我真的很感激。再问一个问题。如果我在 test.Add(sSite, sBldg) 调用 sBldg 中添加了第二个值,有没有办法使用 indexOf 找到该值的位置?
  • 您可以将 sBldg 添加到查询中,如 test.Where(i =&gt; i.Site == sSite &amp;&amp; i.Building == sBldg).FirstOrDefault(),假设您有一个属性“Building”,该属性在您的 Add(sSite,sBldg) 方法中以与“Site”相同的方式初始化。
【解决方案2】:

假设你一开始就有这个:

Location loc = new Location();
loc.Site = "test";

你会得到你的索引。

这也有点令人困惑,因为很不清楚你想在这里完成什么。 注意这行代码:

test.Where(i => i.Site == site).FirstOrDefault();

仅当以下情况为真时才会返回值:“i.Site == site”,当然,如果您提供列表中不存在的内容,则不会发生这种情况。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-29
    • 2013-06-06
    • 1970-01-01
    相关资源
    最近更新 更多