How can I get the unique first letter of names and the number of names starting with that letter from SQL Server using LINQ?
I was playing around with ASP.NET MVC 1.0 a couple of days ago. I started with a single DB table named "Contacts", with a very simple structure for example. Title, FullName, SurName, Email, Phone, Address, etc.
I am using LINQ as my model.
In my main view, I wanted to display a list of alphabets that have matching full names starting with that alphabet plus a number of full names. Similar as below:
A - (2)
D - (4)
J - (1)
and so on. One feature of the display is that I don't want to display alphabets that don't have names starting with them.
I tried a couple of requests but couldn't. Any help with this issue is appreciated. Provide the code in VB.NET language.
Thanks.
a source to share
There is an example on MSDN that is very similar:
public void Linq41() {
string[] words = { "blueberry", "chimpanzee", "abacus", "banana", "apple", "cheese" };
var wordGroups =
from w in words
group w by w[0] into g
select new { FirstLetter = g.Key, Words = g };
foreach (var g in wordGroups) {
Console.WriteLine("Words that start with the letter '{0}':", g.FirstLetter);
foreach (var w in g.Words) {
Console.WriteLine(w);
}
}
}
You will need to change Words = g to Count = g.Count in the select statement so that you only ask for the total of the items in the group.
a source to share