【问题标题】:C# List of objects binary search with a comparer带有比较器的 C# 对象列表二进制搜索
【发布时间】:2014-02-23 07:16:27
【问题描述】:

我有一个名为 Artist 的对象。

public class Artist
{
    public string artistID { get; set; }
    public string artistName { get; set; }

    public Artist(string artistID, string artistName)
    {
        this.artistID = artistID;
        this.artistName = artistName;

    }

    public Artist()
    {
    }
    public Artist(string artistID)
    {
        this.artistID = artistID;
    }

有一个像这样的自定义比较器:

public class CompareArtists : IComparer<Artist>
{

  public int Compare(Artist x, Artist y)
  {
      if (x.artistID == null) return -1;
      if (y.artistID == null) return 1;

    return String.Compare(x.artistID, y.artistID);
   }

}

我正在尝试查看某个艺术家是否包含在我的主程序的艺术家列表中。我正在这样做:

Artist tempArtist = new Artist(user[1]);
Artist result = new Artist();

position = artists.BinarySearch(tempArtist, dc);
result = artists.ElementAt(position);
                       users.ElementAt(counter).favoriteArtists.Add(result,Int32.Parse(user[2]));

二进制搜索的结果是一个负数,从我在 MSDN 上读到的,是下一个最大索引的补码。并且在没有找到结果时显示。但是,我 100% 确定我在艺术家列表中搜索的项目确实存在。 当我使用线性方法时,例如Artists.Single 或 Artists.Find,我得到一个结果。

您发现我的比较器或我使用二分搜索的方式有什么问题吗?

ps:dc 是我的比较器:CompareArtists dc = new CompareArtists(); user[] 是一个字符串数组,它是从我用流阅读器读取的一行中拆分出来的。它包含 [1] 处的艺术家 ID 提前谢谢

【问题讨论】:

  • 你的列表排序了吗?因为您只能在排序列表上使用BinarySearch
  • 另外请注意,如果您的比较器呈现给两个艺术家,他们的 ID 为空,则比较器会做错事。在这种情况下它应该返回 0。
  • 该列表是通过读取 ID 实际排序的文件顺序生成的。所以我会说是的。如果这就是你的意思
  • 什么是直流? Dinocomparer?

标签: c# list binary-search


【解决方案1】:

您需要在BinarySearch 之前对列表进行排序,请参阅documentation

使用指定的比较器在整个排序的列表中搜索元素并返回元素的从零开始的索引。

artists.Sort(new CompareArtists());
position = artists.BinarySearch(tempArtist, dc);

您还应该在 SortBinarySearch 中使用相同的比较器以使其工作

【讨论】:

  • 你说得对,我想因为列表是按顺序生成的,所以它实际上是有序的。但是在对艺术家列表进行排序后,我的代码就可以工作了。我很困惑,但它有效。
  • 快速跟进。我实际上是将它们作为字符串进行比较,在我的顺序生成中,它们被排序为整数。作为字符串,排序是不同的。这就是它不起作用的原因。
猜你喜欢
  • 2010-11-11
  • 2015-07-29
  • 1970-01-01
  • 2022-11-25
  • 2016-03-17
  • 2011-05-02
  • 2023-01-13
  • 2012-09-16
  • 1970-01-01
相关资源
最近更新 更多