我上课Value
:
class Value
{
public Guid Guid {get;set;}
public double Val {get;set;}
}
所以,如果我有两个Value
的大列表,我该如何对它进行排序然后使用BinarySearch?
我能做到吗? 谢谢!
答案 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();