Select from a dictionary the list with the least elements

1

I have a concurrentDictionary in which it contains a list. I would like to know how I can get the Key from the list with fewer elements.

ConcurrentDictionary<string, List<object>> _listInfo = null;

For example, imagine that the dictionary contains 4 records with the following values:

key(string) | lista(object)
    1          1,2,3,4
    2          1
    3          1,2,3,4,5
    4          1,2

The idea is to make a query about the dictionary and to return Key 2, which is the one with the fewest elements.

    
asked by Sergio 14.09.2017 в 16:00
source

1 answer

3

There is a very simple solution using Linq's method OrderBy . Simply sort your list by the number of elements of the Value and return the first:

var resultado = _listInfo.OrderBy(x => x.Value.Count).First().Key;

You must bear in mind that if the collection has no elements this code will give an exception, so you must control this possibility or use FirstOrDefault instead of First , which will return null in case the collection be empty.

As a demonstration that in programming there are always several ways to do the same thing, I put another solution using the methods Where and Min :

var resultado = _listInfo.Where(x => x.Value.Count == _listInfo.Min(y => y.Value.Count))
                         .FirstOrDefault().Key;

Finally, a "classic" solution with a loop:

int numElementosMenor=int.MaxValue;
string keyDelMenor = "";
foreach(var v in _listInfo)
{
    int numelementos = v.Value.Count;
    if (numelementos < numElementosMenor)
    {
        keyDelMenor = v.Key;
        numElementosMenor = numelementos;
    }
}
    
answered by 14.09.2017 / 16:12
source