C#稍微复杂的linq

Joh*_*n D 2 c# sql linq

之前我在检索数据服务器端的数量时询问了一个问题,并在网站上提供了解决方案.建议是使用linq,但是因为我比较新,所以我需要一点深入的帮助.

使用John的解决方案:

class Guy
{
    public int age; public string name;
    public Guy( int age, string name ) {
        this.age = age;
        this.name = name;
    }

}

class Program
{
    static void Main( string[] args ) {
        var GuyArray = new Guy[] { 
        new Guy(22,"John"),new Guy(25,"John"),new Guy(27,"John"),new Guy(29,"John"),new Guy(12,"Jack"),new Guy(32,"Jack"),new Guy(52,"Jack"),new Guy(100,"Abe")};

    var peeps = from f in GuyArray group f by f.name into g select new { name = g.Key, count = g.Count() };

        foreach ( var record in peeps ) {
            Console.WriteLine( record.name + " : " + record.count );
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

我可以按照约翰的建议使用上面的约翰,杰克和安倍的事件计数.但是如果问题稍微复杂一点怎么办呢

var GuyArray = new Guy[] { 
new Guy(22,"John", "happy"),new Guy(25,"John", "sad"),new Guy(27,"John", "ok"),
new Guy(29,"John", "happy"),new Guy(12,"Jack", "happy"),new Guy(32,"Jack", "happy"),
new Guy(52,"Jack", "happy"),new Guy(100,"Abe", "ok")};
Run Code Online (Sandbox Code Playgroud)

上面的代码非常适合检索不同名称的出现次数,但如果我需要名称的出现次数以及每个人的快乐,悲伤或确定的出现次数,该怎么办呢.即输出是:名称,名称计数,满意的名字计数,悲伤的名称数,可以的名称数.如果linq不是最好的解决方案,我准备听取所有替代方案.非常感谢您的帮助.

jas*_*son 7

坦率地说,目前尚不清楚你是否想要幸福的总人数,或者想要通过名字感到满意的总人数(也是为了悲伤,好吧).我会给你一个解决方案,可以给你两个.

var nameGroups = from guy in GuyArray 
                 group guy by guy.name into g
                 select new { 
                     name = g.Key,
                     count = g.Count(),
                     happy = g.Count(x => x.status == "happy"),
                     sad = g.Count(x => x.status == "sad"),
                     ok = g.Count(x => x.status == "ok")
                 };
Run Code Online (Sandbox Code Playgroud)

然后:

foreach(nameGroup in nameGroups) {
    Console.WriteLine("Name = {0}, Count = {1}, Happy count = {2}, Sad count = {3}, Okay count = {4}", nameGroup.name, nameGroup.count, nameGroup.happy, nameGroup.sad, nameGroup.ok);
}
Run Code Online (Sandbox Code Playgroud)

如果你想要完全快乐,悲伤,好的计数,你可以说:

Console.WriteLine(nameGroups.Sum(nameGroup => nameGroup.happy));
Run Code Online (Sandbox Code Playgroud)

等等

另外,你应该做一个枚举

public enum Mood {
    Happy,
    Sad,
    Okay
}
Run Code Online (Sandbox Code Playgroud)

然后

class Guy {
    public int Age { get; set; }
    public string Name { get; set; }
    public Mood Mood { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这样你就可以写:

var people = from guy in guyArray 
             group guy by guy.Name into g
             select new { 
                 Name = g.Key,
                 Count = g.Count(),
                 HappyCount = g.Count(x => x.Mood == Mood.Happy),
                 SadCount = g.Count(x => x.Mood == Mood.Sad),
                 OkayCount = g.Count(x => x.Mood == Mood.Okay)
             };
Run Code Online (Sandbox Code Playgroud)