Home > Mobile >  A method that receives a list<strings> and a int n, returns the word that repeats n times in t
A method that receives a list<strings> and a int n, returns the word that repeats n times in t

Time:09-02

I tried to do a foreach but I don't know how to save the iteration for the words and compare with the integer

var words = new List<String> {"Mike", "Mia" ,"Mike", "Frank" ,"Mike", "Lisa", "Joss", "Frank" };
int number = 3;

String find(List<String> lst, int n) 
{
  //what goes here?
}

CodePudding user response:

Here you go:

var result = lst.GroupBy(x=> x).Where(x=> x.Count() == n).Select(x=> x.Key).FirstOrDefault();

CodePudding user response:

https://dotnetfiddle.net/TWaSGg

I modified it a bit to return all strings that were repeated 'n' times though

                    
public class Program
{
    public static void Main()
    {
        var words = new List<String> {"Mike", "Mia" ,"Mike", "Frank" ,"Mike", "Lisa", "Joss", "Frank" };
        int number = 3;
        var result = find(words,number);
        Console.WriteLine(string.Join(",",result));
    }
    
    

private static IList<string> find(List<String> lst, int n) 
{
  
    return  lst.GroupBy(x=>x).Where(y=>y.Count()==n).Select(val=>val.Key).ToList();
    
}
}
  • Related