我需要用三个给定的项目来获取 a 的索引Tuple<string,string,string,string>
,List
但第四个是什么并不重要。前任:
Listoftuples.IndexOf(new Tuple<string,string,string,string>("value1","value2","value3","this value does not matter"))
在索引方面是否有通配符,或者有不同的方法来解决这个问题?
int index = Listoftuples.FindIndex(t => t.Item1 == "value1" && t.Item2 == "value2" && t.Item3 == "value3");
您可能想要创建一个函数来创建谓词:
Func<Tuple<string,string,string,string>, bool> CreateMatcher(string first, string second, string third)
{
return t => t.Item1 == first && t.Item2 == second && t.Item3 == third;
}
那么你可以使用
int index = Listoftuples.FindIndex(CreateMatcher("value1", "value2", "value3"));
没那么复杂。这是一个通用的辅助方法:
public static int IndexOf<TSource, TKey>(this IEnumerable<TSource> source, TKey key
, Func<TSource, TKey> selector)
{
int i = 0;
foreach (var item in source)
{
if (object.Equals(selector(item), key))
return i;
i++;
}
return -1;
}
现在您有了一个IndexOf
采用选择器的方法,它很简单:
list.IndexOf(Tuple.Create("value1", "value2", "value3")
, item => Tuple.Create(item.Item1, item.Item2, item.Item3));
请注意,如果您想让它更通用,可以将一个IComparer<TKey>
作为可选参数添加到该方法。IndexOf
虽然 Oded 的回答是(是)正确的,但 Linq 有一个内置的方法来做几乎所有基于列表的事情,所以你不必自己动手。
var myElement = (Listoftuples.Select((x,i)=>new {Index = i,
Element = Tuple.Create(x.Item1, x.Item2, x.Item3})
.FirstOrDefault(a=>a.Element == TupleToSearchFor);
var myIndex = myElement == null ? -1 : myElement.Index;
分解它:
Select() 方法有一个重载,它接受带有两个参数的 lambda;源可枚举的当前元素和源中该元素的“索引”(请了解这仅对我们有效,因为我们不会更改原始列表中任何元素的顺序;如果我们首先对其进行排序,则索引Listoftuple 和传递给 Select() 的元素之间不匹配。
然后我们使用这个方法来生成匿名类型的元素,它为我们做了两件事;首先,我们可以将 Tuple 更改为三个值的 Tuple(每个源 Tuple 的前三个,这是我们关心的),其次,我们可以相对轻松地“固定”原始元素的索引列表供以后参考。
FirstOrDefault() 遍历 Select() 调用的结果,直到它找到一个元组与我们正在搜索的元素匹配的元素(或者它没有找到任何东西,在这种情况下它返回 null)。
因为 FirstOrDefault() 可能返回 null,所以我们需要检查它。有很多方法可以做到这一点;我用三元语句输入的那个很简单易懂。
最后,myIndex 将具有 Listoftuples 的第一个匹配元素的索引,即 -1,这意味着 Listoftuples 的所有元素都与您搜索的元素不匹配。