Linq常用List操作总结,ForEach、分页、交并集、去重、SelectMany等

/*
以下围绕Person类实现,Person类只有Name和Age两个属性
一.List<T>排序
1.1 List<T>提供了很多排序方法,sort(),Orderby(),OrderByDescending().
*/

lstPerson = lstPerson.OrderByDescending(x=>x.Name).ToList(); //降序
lstPerson = lstPerson.OrderBy(x => x.Age).ToList();//升序

//通过Name和Age升序
lstPerson.Sort((x, y) =>
            {
                if ((x.Name.CompareTo(y.Name) > 0) || ((x.Name == y.Name) && x.Age > y.Age))
                {
                    return 1;
                }
                else if ((x.Name == y.Name) && (x.Age == y.Age))
                {
                    return 0;
                }
                else
                {
                    return -1;
                }
            });

/*
1.2 因为最近有做datagrid里面像实现点击任何一列的名称就按照该名称排序,那我们该怎么做呢?可能第一反应是想,为每一个属性写一个排序方法不就得了,其实这样的话无意间增加的代码量了,而且不通用,其实这里可以结合反射来实现.
*/

string propertityName = "Name";
lstPerson = lstPerson.OrderBy(x =>
            {
                PropertyInfo[] proInfos = x.GetType().GetProperties();
                return proInfos.Where(info => info.Name == propertityName).ToList()[0].GetValue(x);
            }).ToList();

/*
二.List<T>分页
2.1往往有时候我们会从后台获取很多数据,存放在List<T>,可是因为界面受限制无法完全展示,我们就会想到分页显示,对于分页显示我们基本上第一种想法肯定是通过循环设置每一页的Size,
其实linq有skip和take方法,skip表示跳过多少元素,take获取特定个数元素. 看起来代码简洁多了.
*/

public static List<Person> GetPageByLinq(List<Person> lstPerson, int pageIndex, int PageSize)
{
    return lstPerson.Skip((pageIndex - 1) * PageSize).Take(PageSize).ToList();
}

/*
三,List<T>之foreach用法.
2.1 如何我相对List里面的每个对象执行相同操作的话,以前都是通过for循环遍历,其实Linq提供了便捷的Foreach来实现。下面我将对所有的Person年龄+2.
*/

lstPerson.ForEach(x => x.Age= x.Age + 2);

/*两个集合之间操作*/
List<string> ListResult = new List<string>();
ListResult = ListA.Distinct().ToList();//去重
ListResult = ListA.Except(ListB).ToList();//差集
ListResult = ListA.Union(ListB).ToList();  //并集
ListResult = ListA.Intersect(ListB).ToList();//交集

//这里有7个老师,每个人有3个学生,总共21一个学生里,我们想要获得这3个未及格的学生集合。
public class Student
{
	public string StudentName { get; set; }
	public int Score { get; set; }

	public Student(string StudentName,int Score)
	{
		this.StudentName = StudentName;
		this.Score = Score;
	}
}
public class Teacher
{
	public string TeacherName { get; set; }
	public List<Student> Students { get; set; }
	public Teacher(string TeacherName, List<Student> Students)
	{
		this.TeacherName = TeacherName;
		this.Students = Students;
	}
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestLinq
{
    class Program
    {
        static void Main(string[] args)
        {
            //运行结果见下图
            List<Teacher> teachers = new List<Teacher>
            {
                new Teacher("张老师",new List<Student>{ new Student("张三1", 100),new Student("李四1", 90),new Student("王五1", 30) }), //
                new Teacher("李老师",new List<Student>{ new Student("张三2", 100),new Student("李四2", 90),new Student("王五2", 60) }),
                new Teacher("赵老师",new List<Student>{ new Student("张三3", 100),new Student("李四3", 90),new Student("王五3", 40) }), //
                new Teacher("孙老师",new List<Student>{ new Student("张三4", 100),new Student("李四4", 90),new Student("王五4", 60) }),
                new Teacher("钱老师",new List<Student>{ new Student("张三5", 100),new Student("李四5", 90),new Student("王五5", 50) }), //
                new Teacher("周老师",new List<Student>{ new Student("张三6", 100),new Student("李四6", 90),new Student("王五6", 60) }),
                new Teacher("吴老师",new List<Student>{ new Student("张三7", 100),new Student("李四7", 90),new Student("王五7", 60) })
            };

            #region 所有任课老师下未及格的学生 方式一
            List<Student> studentList = new List<Student>();
            foreach (var t in teachers)
            {
                foreach (var s in t.Students)
                {
                    if (s.Score < 60)
                    {
                        studentList.Add(s);
                    }
                }
            }
            studentList.ForEach(s => Console.WriteLine(string.Format("{0} - {1}", s.StudentName, s.Score)));
            #endregion

            Console.ReadKey();

            #region 所有任课老师下未及格的学生 方式二
            var list1 = from t in teachers
                        from s in t.Students
                        where s.Score < 60
                        select s;
            foreach (var item in list1)
            {
                Console.WriteLine(string.Format("{0} - {1}", item.StudentName, item.Score));
            }
            #endregion

            Console.ReadKey();

            #region 所有任课老师下未及格的学生 方式三
            var list2 = teachers.SelectMany(t => t.Students).Where(s => s.Score < 60);

            foreach (var s in list2)
            {
                Console.WriteLine(string.Format("{0} - {1}", s.StudentName, s.Score));
            }
            #endregion

            Console.ReadKey();

            #region 所有未及格的学生及其授课老师 
            var list3 = teachers.SelectMany(
                t => t.Students,
                (t, s) => new { t.TeacherName, s.StudentName, s.Score })
                .Where(n => n.Score < 60);

            foreach (var item in list3)
            {
                Console.WriteLine(string.Format("任课老师{0} - 学生{1} 分数{2}", item.TeacherName, item.StudentName, item.Score));
            }
            #endregion
            Console.ReadKey();
        }
    }
}



posted @ 2016-10-21 14:58  深南大道  阅读(366)  评论(0编辑  收藏  举报