LINQ query required to search for string elements

I have a List<NameClass> that stores a collection of NameClass elements with a property called Name in the class. What I'm trying to do is write a Linq query that will pull out all the names starting with Jones , but only if there are 3 or more cases. For example, if my list had the following items:

 Name ----------- Jones Jonestown Smith Hector Jones Smith Smith 

I am looking for a C # function that I can call as follows:

 GetNames("Jones"); 

And he must return:

 Jones Jonestown Jones 

And if I run this:

 GetNames("Smith"); 

He must return:

 Smith Smith Smith 

And if I run this:

 GetNames("Hector"); 

It should not return anything, since the Hector not in the list 3 or more times.

Any help in writing this LINQ query would be appreciated!

+1
source share
6 answers
 string searchString = "Jones"; string lowerSS = searchString.ToLower(); List<NameClass> nameClasses; var results = nameClasses.Where(nc => nc.Name.ToLower().StartsWith(lowerSS)); if(results != null && results.Count() >= 3) { return results; } else { return null; } 
+5
source

I think you're looking for something like that, right?

 public static IEnumerable<NameClass> GetNames(IEnumerable<NameClass> names, String name, int minCount) { var matchingNames = names.Where(n => n.Name.StartsWith(name)); if (matchingNames.Count() >= minCount) { return matchingNames.ToList(); } else { return null; } } var jones = GetNames(names, "Jones", 3); 
+2
source

Have you tried this?

 public void GetNames(string pattern) { var q = from n in names where n.Name.StartsWith(pattern) select n; if (q.Count() >= 3) return q.ToList(); else return new List<NameClass>(); } 
+2
source
 IEnumerable<NameClass> GetNames(string s, List<NameClass> list) { var filtered = list.Where(l => l.Name.StartsWith(s)); return filtered.Count() >= 3 ? filtered : null; } 
+2
source

If you do not need all of this in a single request, this extension method should do this:

 public static IEnumerable<string> GetNames(this IEnumerable<string> list, string prefix, int minOccurences) { var res = list.Where(x => x.StartsWith(prefix)); return res.Count() >= minOccurences ? res : new string[0]; } 
+1
source

A "single insert":

 public string[] GetNames(MyClass[] list, string prefix) { return list .Where(item => item.Name.StartsWith(prefix) && list.Count(temp => temp.Name.StartsWith(prefix)) > 2) .Select(l => l.Name) .ToArray(); } 
+1
source

All Articles