djskj189 djskj189 - 1 year ago 85
C# Question

Find least occurring members in the list

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 occuring values in the list?

Thanks for your help

If the question is unclear, please let me know. Ill modify asap

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download