我可以对guids列表进行排序并进行二分查找吗?

时间:2016-02-17 07:46:45

标签: c# guid binary-search

我上课Value

class Value
{
   public Guid Guid {get;set;}
   public double Val {get;set;}
}

所以,如果我有两个Value的大列表,我该如何对它进行排序然后使用BinarySearch?

我能做到吗? 谢谢!

2 个答案:

答案 0 :(得分:3)

要点:

如果您有Value的列表,并且想要根据Guid对列表进行排序,那么您有两种可能性。您可以通过所需的属性显式对列表进行排序,也可以实现IComparable<Value>

var orderedList = list.OrderBy(i => i.Guid);

另一种情况是:

public class Value: IComparable<Value>
{
    public int CompareTo(Value other)
    {
        if(other == null)
        {
            return 1;
        }
        return Guid.CompareTo(other.Guid);
    }
    //[...]
}

然后你可以排序:

var orderedList = list.OrderBy(i => i).ToList();

然后,当您想要执行二进制搜索时,只需应用以下行:

int index = orderedList.BinarySearch(new Value{ Guid = guidToSearchFor });

实施例

using System.IO;
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        List<Value> list = new List<Value>
        {
            new Value() { Guid = Guid.NewGuid() },
            new Value() { Guid = Guid.NewGuid() },
            new Value() { Guid = Guid.NewGuid() },
            new Value() { Guid = Guid.NewGuid() }
        };

        var orderedList = list.OrderBy(i => i).ToList();
        int index = orderedList.BinarySearch(new Value{ Guid = list[2].Guid });
        Console.WriteLine(index);
    }
}

public class Value: IComparable<Value>
{
    public int CompareTo(Value other)
    {
        if(other == null)
        {
            return 1;
        }
        return Guid.CompareTo(other.Guid);
    }

    public Guid Guid {get;set;}
    public double Val {get;set;}
}

答案 1 :(得分:0)

List<Value> valList = new List<Value>();成为Value的列表然后您可以根据属性Val对其进行排序,如下所示:

 valList = valList.OrderBy(x => x.Val).ToList();