djskj189 djskj189 - 10 months ago 46
C# Question

Find least occurring members in the list in C#

I have

with random amount of entries (somewhere between 10-500). and I need to find the value that occurs the least number of time. For example,
list<string> myList
100 "a", 50 "b", 2 "c", and 1 "d"
, and I wish to extract "c" and "d". My problem is that I will never know the exact number of each string, and exact name of the string in the list.

For similar analogy, examine the code below:

public class Program
public static void Main(string[] args)
Random r = new Random();

int randomNumber = r.Next(5,15);
int randomRangeOne = r.Next(0,2);
int randomRangeTwo = r.Next(0,2);

List<int> randomList = new List<int>();

for(int i = 0; i < 1000; i++)
int x = r.Next(randomNumber - randomRangeOne, randomNumber + randomRangeTwo);

In this case (in the actual problem, it is random string, not random int), how would I extract least occurring values in the list?

Answer Source

Here is a simple LINQ

var leastOccured = data
    .GroupBy(x => x)
    .OrderBy(group => group.Count())
    .Select(x => x.Key)

You group same strings, sort them by number of each group ascending and take the first one which is the least occurred string in least.

If there can be many strings with same occurrence count you can use the code below

var ordered = data
    .GroupBy(x => x)
    .Select(group => new { group.Key, Count = group.Count() })
    .OrderBy(x => x.Count);

var minOccurrenceCount = ordered.First().Count;

var leastOccurredStrings = ordered 
    .TakeWhile(x => x.Count == minOccurrenceCount)
    .Select(x => x.Key);