我可以排序向导列表并进行二进制搜索吗?
作者:互联网
我上课的价值:
class Value
{
public Guid Guid {get;set;}
public double Val {get;set;}
}
因此,如果我有两个很大的值列表,该如何对它进行排序,然后使用BinarySearch?
我可以做吗?
谢谢!
解决方法:
摘要:
如果您有“值”列表,并且想要根据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;}
}
标签:binary-search,guid,c 来源: https://codeday.me/bug/20191119/2032927.html