C#Linq最接近目标元素的索引

时间:2017-10-30 10:21:57

标签: c# linq

是否可以创建linq来查找C#4.0中目标元素的最近索引? 例如,我有一个数组

string[] array=new string[] 
{"","","source","","source2","","","destination","source3","destination"};

"目的地"发现在7和9,最近的指数"目的地"到2("来源")应该是7而不是9。

我知道使用if条件的当前解决方案,

int index(int sourceIndex,string[] array,string destination)
{
    int temp=sourceIndex;
    while(temp<array.Length)
    {
        if(array[sourceIndex]==destination)
            return sourceIndex;
        temp++;
    }
    return -1;
}

编辑添加: 我需要找到目的地在前进方向的增加顺序 提前致谢

3 个答案:

答案 0 :(得分:4)

如果你确实有一个数组,我认为你不需要使用Linq。

这样做会简单得多:

int startIndex = 2;
int nearest = Array.IndexOf(array, "destination", startIndex+1);

然后nearest将包含您要查找的结果,如果找不到"destination"则为-1。

注意:这只能找到最接近前向的方向,我认为这是你想要的语句:“源索引是已知的并且在前进方向最近,如果没有出现,则不需要返回“

另请注意,我使用了startIndex+1,因为我们无需在第一个位置开始搜索。

答案 1 :(得分:1)

不一定是最有效的解决方案,但是如果你不期望很多匹配它应该有效:

string[] array = new string[] {"","","source","","source2","","","destination","source3","destination"};
var withIndex = array.Select((Value, Index) => new { Index, Value });
var result = 
    (from dest in withIndex.Where(_ => _.Value == "destination")
    from source in withIndex.Where(_ => _.Value == "source")
    let dif = dest.Index - source.Index
    orderby dif
    select dest.Index)
    .FirstOrDefault();

我们首先出现sourcedestination,我们找到最小的差异。

答案 2 :(得分:1)

如果确实想要使用linq(比如你有IEnumerable而不是真正的数组),你可以这样做:

static int index(int sourceIndex, IEnumerable<string> array, string destination)
{
    return array
        // convert items stream into (item, index) pair
        .Select((item, index) => new { Item = item, Index = index })
        // skip items until condition is met
        .SkipWhile(c => c.Index <= sourceIndex || c.Item != destination)
        // we need index only
        .Select(c => c.Index)
        // if we found nothing - return -1
        .DefaultIfEmpty(-1)
        .First();            
}

如果您有阵列 - 请不要这样做并使用Matthew Watson的答案。