0

几天前我在玩 ASP.NET MVC 1.0。我从一个名为“Contacts”的单表数据库开始,其结构非常简单,例如 Title、FullName、SurName、Email、Phone、Address 等。

我使用 LINQ 作为我的模型。

在我的主视图中,我想显示一个字母列表,这些字母具有以该字母开头的全名加上全名的计数。类似如下所示:

A - (2)
D - (4)
J - (1)
以此类推。关于显示的一件特别的事情是我不想显示那些没有以它们开头的名字的字母。

我尝试了几个查询,但没有成功。感谢您对解决此查询的任何帮助。请提供 VB.NET 语言的代码。

谢谢。

4

3 回答 3

3
    var query = from c in contacts
                group c by c.FullName[0] into cg
                select new { FirstChar = cg.Key, Count = cg.Count() };

应该管用

于 2009-05-16T17:53:21.143 回答
0

MSDN上有一个非常相似的例子:

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);
                }
            }
        }

您必须在 select 语句中将 Words = g 更改为 Count = g.Count,因此您只需查询组中项目的总和。

于 2009-05-16T17:53:37.833 回答
0

在 VB.NET 中:

Dim FirstLetterCounts = From c In contacts _
                        Group c By Key = c(0) Into NameGroup _
                        Select FirstLetter = Key, Count = NameGroup.Count()

For Each g In FirstLetterCounts
    Console.WriteLine("First Letter = {0}, Count = {1}", g.Key, g.Count)
Next
于 2009-05-16T17:59:47.743 回答