-4

So the issue I'm running into is I'm wanting to count the multiples of an enum within a list. Say, for example, I have a List of "Hi" "Hi" "Hello" "Hi" and "Hello".

Is there a way in which I can search the array and find out that there is 3 of the "Hi" without having to do the List.Where x = "Hi">?

Thanks a ton.

  • And then what about "Hello"? Are you going to test that too? Please post your c# code. – Delphi.Boy Apr 06 '15 at 15:33
  • I would like to find out if "Hello" has multiples too. From what I've found online, and my basic knowledge of c# I've only seen the .Where<> capabilities however I have to predefine what enum or string I'm trying to find in the list. I'm wondering if there was a way to have it just count the enums or strings themselves and return their are multiples. – Dustin Taylor Apr 06 '15 at 15:36
  • So you want a resulting list that contains only enums that are mutiples ?? – Coder1409 Apr 06 '15 at 15:39
  • What have you tried yourself so far? If you can post your current (non-preferable) way of doing it, that would be very helpful – Fred Kleuver Apr 06 '15 at 15:46
  • possible duplicate of [c#: a method to count occurrences in a list](http://stackoverflow.com/questions/1139181/c-a-method-to-count-occurrences-in-a-list) – pangabiMC Apr 06 '15 at 15:56

7 Answers7

2

You can try Linq to compute frequencies, e.g.:

List<String> source = new List<string>() {
  "Hi", "Hi", "Hello", "Hi", "Hello"
};

Dictionary<String, int> freqs = source
  .GroupBy(item => item)
  .ToDictionary(item => item.Key,
                item => item.Count());

....
int freqHi = freqs["Hi"]; // 3
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

To count the number of occurrences of a certain element in a list, you can simply do:

List.Count(x => x == "Hi");

EDIT: If you just want an short-hand way of telling which element occurs N times, you could accomplish that with a nested query:

List<string> greetings = new List<string> {"Hi", "Hi", "Hello", "Hello", "Hi"};

List<string> greetingsThatOccurThreeTimes = greetings
    .Where(s1 => greetings.Count(s2 => s1 == s2) == 3).ToList();

EDIT #2: You could also clean this up by using extension methods.

By declaring this:

public static class ListExtensions
{
    public static List<T> WithNOccurrences<T>(this List<T> source, int n)
    {
        return source.Where(s1 => source.Count(s2 => s1.Equals(s2)) == n).ToList();
    } 
}

You could do something like this in your calling code:

List<string> greetings = new List<string> {"Hi", "Hi", "Hello", "Hello", "Hi"};

// This list will only contain "Hi" (but 3 times, though)
List<string> greetingsThatOccurThreeTimes = greetings.WithNOccurrences(3);

This should more closely resemble your "ThreeOfAKind == true".

If you only want to get back one of each item that occurs N times, simply add .Distinct() to the extension method, like so:

public static class ListExtensions
{
    public static List<T> WithNOccurrences<T>(this List<T> source, int n)
    {
        return source
            .Where(s1 => source.Count(s2 => s1.Equals(s2)) == n)
            .Distinct().ToList();
    } 
}
Fred Kleuver
  • 7,797
  • 2
  • 27
  • 38
  • Well, what I was thinking is something like there are 3 hi's in the list and 2 hellos. We want to count the multiples of those items. These items may work in a list.GroupBy<> function, however I was wondering if there was a way where we could have "threeofAkind = true" when we iterate through the list and find three of the "hi" in the list. – Dustin Taylor Apr 06 '15 at 15:42
  • I have added an extension method which does just about that. Is that what you were looking for? – Fred Kleuver Apr 06 '15 at 15:57
  • This is exactly what I was looking for. Thank you. I am relatively new to coding and let's just say college doesn't exactly teach us things like this. – Dustin Taylor Apr 06 '15 at 16:21
  • I don't think you'd **want** college teaching you stuff like this - it's not really that important from a fundamentals perspective. You pick these little "extra's" up along the way. Don't forget to accept the answer that you think answers your question :) – Fred Kleuver Apr 06 '15 at 16:35
0

This Linq Query will give you the list of items which have duplicates

 var mutiples = l.GroupBy(e => e).Where(c=>c.Count()>1);

you can iterate over the mutiples list using this code

 foreach (var pair in mutiples)
            Console.WriteLine(pair.Key + " " + pair.Count());
Coder1409
  • 523
  • 4
  • 12
0

Here you go:

        public List<string> GetDuplicates(List<string> list)
        {
            var q = from s in list
                    group s by s into g
                    select new { str = g.Key, count = g.Count() };

            return q.Where(str => str.count > 1).Select(str => str.str).ToList<string>();
        }
Delphi.Boy
  • 1,199
  • 4
  • 17
  • 38
0
string words = "Hi, Hi, Hello, Hi, Hello";
var countList = words.Split(new[] { " " }, StringSplitOptions.None);
int count = countList.Where(s => s.Contains("Hi")).Count();

count = 3 when running this code.

MethodMan
  • 18,625
  • 6
  • 34
  • 52
0

You have to group them first, and then perform a selection operation. If you are asking to count them, an example can be:

List<string> stringList = new List<string>{ "hi", "hi", "hi", "hello" };
stringList.GroupBy(i => i).Select(i => new {i.Key, i.ToList().Count }).ToList();
Touhid Alam
  • 343
  • 1
  • 5
0

See this SO post https://stackoverflow.com/a/10812657/1339616

You can also use the LINQ query syntax like this.

from    s in new List<string> {"Hi", "Hi", "Hello", "Hi", "Hello"}
group   s by s into g
where   g.Count() > 1
orderby g.Count() descending
select  new {Key = g.Key, Count = g.Count() }
Community
  • 1
  • 1
mrrodd
  • 126
  • 1
  • 6