Reputation: 48686
I have a List<NameClass>
that stores a collection of NameClass
items with a property called Name
in the class. What I'm trying to do is write a Linq query that will pull all the names that start with Jones
, but only if there are 3 or more occurrences. 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 like this:
GetNames("Jones");
And it should return:
Jones
Jonestown
Jones
And if I run this:
GetNames("Smith");
It should return:
Smith
Smith
Smith
And if I run this:
GetNames("Hector");
It should return nothing since Hector
isn't in the list 3 or more times.
Any help writing this LINQ query would be appreciated!
Upvotes: 1
Views: 9555
Reputation: 16623
IEnumerable<NameClass> GetNames(string s, List<NameClass> list)
{
var filtered = list.Where(l => l.Name.StartsWith(s));
return filtered.Count() >= 3 ? filtered : null;
}
Upvotes: 2
Reputation: 139758
A "one liner":
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();
}
Upvotes: 1
Reputation: 460108
I think you're looking for something like this, aren't you?
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);
Upvotes: 2
Reputation: 15794
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>();
}
Upvotes: 2
Reputation: 19020
If you don't need it all in one query this extension method should do it:
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];
}
Upvotes: 1
Reputation: 7323
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;
}
Upvotes: 7