获取前x个相等元素的索引

时间:2013-10-03 15:36:20

标签: c# linq

我需要在排序的整数列表中获取彼此相等的所有最大元素的索引。

所以给出了这个列表

elements:   {1 , 1, 2, 3, 4, 4, 5, 6, 7, 7, 8, 9, 10, 11, 11, 12, 13, 13, 13}
index:       0   1  2  3  4  5  6  7  8  9  10 11 12  13  14  15  16  17  18
                                                                  ^   ^   ^

我会得到这个输出

{16,17,18}

到目前为止我已经

list.Select((x, i) => new {x, i})

要获取索引,但我无法将OrderBy()First()Single()一起使用,因为我需要所有最大元素的索引,而不仅仅是最顶层的索引。

有没有一种优雅的方法来实现这一点(使用LINQ或其他方式)?

4 个答案:

答案 0 :(得分:7)

因此对项目进行排序,您只需要获取具有最大值的第一个项目的索引(该项目将与最后一个项目具有完全相同的值),然后创建从该索引开始到列表末尾的索引范围: / p>

var items = new List<int> {1,1,2,3,4,4,5,6,7,7,8,9,10,11,11,12,13,13,13};
int startIndex = items.IndexOf(items[items.Count - 1]);
var indexes = Enumerable.Range(startIndex, items.Count - startIndex);

答案 1 :(得分:0)

简单/懒惰的方式:

        var a = new[] {1, 1, 2, 3, 4, 4, 5, 6, 7, 7, 8, 9, 10, 11, 11, 12, 13, 13, 13};
        var b = new List<int>();
        var max = a.Max();
        for (var i = 0; i < a.Length; i++)
        {
            if (a[i] == max) b.Add(i);
        }

答案 2 :(得分:0)

我不会使用LINQ,因为它是一个简单的foreach而不是集合。

//var data = new[] {1, 1, 13, 2, 3, 4, 4, 5, 6, 7, 7, 8, 9, 10, 11, 11, 12, 13, 13, 13};
var data = new[] {1, 1, 2, 3, 4, 4, 5, 6, 7, 7, 8, 9, 10, 11, 11, 12, 13, 13, 13};

var largest = int.MinValue;
var indices = new List<int>();

foreach (var x in data.Select((value, idx) => new {value, idx}))
{
    if (x.value > largest)
    {
        indices.Clear();
        largest = x.value;
    }

    // if unsorted
    //if (x.value == largest) indices.Add(x.idx);

    // if sorted you don't need to check against largest
    indices.Add(x.idx);
}

Console.WriteLine("largest = {0}; indices = {1}", largest, string.Join(", ", indices));

虽然如果必须使用LINQ,可以使用此选项代替foreach

data.Select((value, idx) => new {value, idx})
    .Aggregate(indices, (idxs, n) =>
    {
        if (n.value > largest)
        {
            idxs.Clear();
            largest = n.value;
        }

        //unsorted
        if (n.value == largest) idxs.Add(n.idx);

        //sorted
        //idxs.Add(n.idx);
        return idxs;
    });

答案 3 :(得分:0)

这将为您提供所有与其索引重复的元素的结果:

var result = elements.Select((value, index) => new { value, index })
             .Where(g => elements.FindAll(v => v == g.value).Count > 1)
             .GroupBy((a) => a.value).OrderByDescending((g) => g.Key).Take(3);
            //I placed Take(3) as example since you said you need to find
            //elements who are equal to each other,so only those that are
            // not distinct(have duplicates) get into the collection.

            //this will loop through the results and display the value(the item
            //on the list) and its respective index.
            foreach (var item in result.SelectMany(g => g))
            {
                string outcome = item.value + " - " + item.index;
                Console.WriteLine(outcome);
            }