75f2975672e73f7223cd9699d0d63f7b
39.GroupBy

LINQ GroupBy 简介

对序列中的元素进行分组。

LINQ GroupBy 代码示例

/****************************************************************************
 * http://sikiedu.com liangxie
 ****************************************************************************/

using System.Collections.Generic;
using System.Linq;
using UnityEngine;

namespace UniRxLesson
{
    public class LINQGroupByExample : MonoBehaviour
    {
        class Student
        {
            public string Name;

            public int Age;
        }

        private void Start()
        {
            var students = new List<Student>()
            {
                new Student {Name = "张三", Age = 50},
                new Student {Name = "张三", Age = 50},
                new Student {Name = "李四", Age = 40}
            };

            var studentGroup4Names = students.GroupBy(student => student.Name);

            foreach (var studentGroup in studentGroup4Names)
            {
                Debug.LogFormat("Group Key:{0}", studentGroup.Key);

                foreach (var student in studentGroup)
                {
                    Debug.LogFormat("Name:{0} Age:{1}", student.Name, student.Age);
                }
            }
        }
    }
}

输出结果为:

Group Key:张三
Name:张三 Age:50
Name:张三 Age:50
Group Key:李四
Name:李四 Age:40
top Created with Sketch.