Longest List in SortedList Lists

I have a SortedList from the lists, and I am interested in finding the KEY that matches the longest list (the list with the most items in it). In code, it looks like this:

// how the list is defined:
var myList = new SortedList<long, List<string>>();

// EXAMPLE data only:
myList.Add(0, new List<string>());
myList[0].AddRange(new []{"a", "b", "c"});

myList.Add(8, new List<string>());
myList[8].AddRange(new []{"1", "2"});

myList.Add(23, new List<string>());
myList[23].AddRange(new []{"c", "d", "e", "f", "g"});

In the above example, the result should be "23", since this is the key that comes with the longest list.

I know how to write this with a for loop, but I think it should just be LINQ related. However, I cannot get the syntax perfectly correct! Any help is appreciated!

+4
source share
4 answers

Perhaps a more efficient way, but you can sort by count (values) in descending order and do the first.

myList.OrderByDescending(m => m.Value.Count()).First().Key;

, , ( ), .

- .

myList.GroupBy(m => m.Value.Count())
      .OrderByDescending(m => m.Key)//I'm the key of the group by
      .First()
      .Select(g => g.Key);//I'm the key of the SortedList

,

myList.Add(24, new List<string>());
myList[24].AddRange(new[] {"a", "b", "c", "d", "e"});

23 24.

from item in myList
let maxCount = myList.Max(x => x.Value.Count())
where item.Value.Count() == maxCount
select item.Key;
+7

, O (n log n), , O (n):

int maxLength = myList.Max(x => x.Value.Count);
var longestKeys = myList.Where(x => x.Value.Count == maxLength).Select(x => x.Key);
+3

MaxBy of morelinq

var key = myList.MaxBy(x => x.Value.Count()).Key;
+3

, , Linq Aggregate :

//Extension method
public static long MaxIndex(this SortedList<long, List<string>> list)
{
    return list.Aggregate(
        new { MaxValue = -1, Key = -1L },
            ((agg, current) => (current.Value.Count.CompareTo(agg.MaxValue) > 0 || agg.Key == -1) ?
        new { MaxValue = current.Value.Count, Key = current.Key } :
        new { MaxValue = agg.MaxValue, Key = agg.Key })).
        Key;
}

// how the list is defined:
var myList = new SortedList<long, List<string>>();

// EXAMPLE data only:
myList.Add(0, new List<string>());
myList[0].AddRange(new[] { "a", "b", "c" });

myList.Add(8, new List<string>());
myList[8].AddRange(new[] { "1", "2" });

myList.Add(23, new List<string>());
myList[23].AddRange(new[] { "c", "d", "e", "f", "g" });

var idx = myList.MaxIndex();

SO: fooobar.com/questions/241419/...

0

Source: https://habr.com/ru/post/1525079/


All Articles