我想要一個通用的方法來找到第一個位置(我們可以將一個索引當作位置),其中給定的數據比一個大而且小於下一個。C#List <T>是否有擴展的FirstBetween方法?
例如,我有一個int列表[12,34,4,65],如果我給一個數字15(它比12和小於34)大,它應該返回1,如果我給一個數字50它應該返回3等
這是我寫的,但我覺得必須有一個更簡單的方法:
public static class ExtensionMethods
{
public static int FirstBetween<T>(this List<T> list, T t)
{
if (list == null)
return -1;
if(t == null)
return -1;
if(list.Count == 0)
return 0;
T item1;
for(int index = 0;index<list.Count;index++)
{
T item2 = list[index];
if(IsBetween(item1,item2,t))
return index;
item1 = item2;
}
return list.Count;
}
private static bool IsBetween<T>(T t1, T t2, T t)
{
if (t1 == null && t2 == null)
return false;
else if(t1==null && t<=t2)//in case of the first item
return true;
else if (t2 == null && t >= t1)//in case of the last item
return true;
else if(t>=t1 && t<=t2)
return true;
else
return false;
}
}
這是未完成的代碼,我覺得這太複雜了,並作爲模板方法它仍然有一些其他問題。
有沒有更簡單的方法來做到這一點?
1)你有什麼試過? 2)看起來很不一致。 –
聽起來不太難,你能告訴我們你試過了什麼嗎? – gdoron
我不得不迭代列表並使用比較來查找結果。我想知道是否有一種簡單的方法來做到這一點。 – Gisway