Linq处理list数据

获取数据列表。

//获取数据列表,Model是类
IList<Model> list = dao.getmx(Model, pageInfo);
//DataTable数据
DataTable dt = ......;

1、GroupBy与group by

复制代码
//GroupBy
//单条件,并返回序列中满足指定条件的第一个元素(相当于list按照user_type去重,可以是多条).
list = list.GroupBy(a => a.user_type).Select(it => it.First()).ToList();

//多条件,使用了匿名函数.
var quary = list.Where(a => a.p_num == "1" || a.c_num == "1")
            .GroupBy(a => new { student_id = a.student_id, user_type = a.user_type })
            .Select(group => new
            {
                student_id = group.Key.student_id,
                user_type = group.Key.user_type,
                Count = group.Count()
            });

//group by
//单条件
var quary = from a in list.Where(a => "1,8".Contains(a.user_type))
            group a by new { a.school } into m
            select new
            {
                school = m.Key.school
            };

//多条件
var quary = from a in list.Where(a => "1,8".Contains(a.user_type))
            group a by new { a.provice, a.school } into m
            select new
            {
                provice = m.Key.provice,
                school = m.Key.school
            };

//quary取值方法
foreach (var item in quary.ToList())
{
    //取值item
}
复制代码

2、Where条件筛选。

复制代码
//将provice=吉林的筛选出来。
list = list.Where(x => x.provice == "吉林").ToList();

//将包含1,5条件的数据筛选出来,相当于sql里的in用法:select * from 表 where user_type in (1,5)
list= list.Where(a => "1,5".Contains(a.user_type)).ToList();

//此处等同于上面
list= list.Where(a => a.user_type == "1" || a.user_type == "5").ToList();

//另一种形式,from开头
IList<Model> query = (from item in list
                      where ("," + projectmodel.ids + ",").Contains("," + item.id + ",")
                      select item).ToList<Model>();
复制代码

3、Select(取list中的id列数据,并按逗号分隔成字符串。例:1,2,3,4,5)

复制代码
//方式一
//分成key-value的数组
string[] id = list.Select(a => a.id.ToString()).ToArray();
//dt是datatable类型的,执行LINQ语句,这里的.AsEnumerable()是延迟发生,不会立即执行,实际上什么都没有发生
string[] id = dt.AsEnumerable().Select(a => a.Field<int>("id").ToString()).ToArray();
//将数组变成1,2,3,4,5的字符串
string ids = string.Join(",", id);

//方式二
//效果等同于foreach循环
foreach (var i in list)
{
    ids += i.id + ",";
}
ids = ids.TrimEnd(',');

上述代码使用LINQ 针对数据集中的数据进行筛选和整理,同样能够以一种面向对象的思想进行数据集中数据的筛选。
在使用LINQ 进行数据集操作时,LINQ 不能直接从数据集对象中查询,因为数据集对象不支持LINQ 查询,所以需要使用AsEnumerable 方法返回一个泛型的对象以支持LINQ的查询操作。 .AsEnumerable()与相对应的.AsQueryable()的区别: 1) AsEnumerable()是 LINQ TO OBJECT,AsQueryable()是 LINQ TO SQL 2) AsEnumerable将一个序列向上转换为一个IEnumerable, 强制将Enumerable类下面的查询操作符绑定到后续的子查询当中。AsQueryable将一个序列向下转换为一个IQueryable, 它生成了一个本地查询的IQueryable包装。 3) AsEnumerable()延迟执行,不会立即执行。当你调用.AsEnumerable()的时候,实际上什么都没有发生。当真正使用对象的时候(例如调用:First, Single, ToList....的时候)才执行。 4) .ToList()立即执行
复制代码

4、Where与Select的同时使用,取list中的joineventids列数据,并按逗号分隔成字符串。

string[] id = list.Where(a => !string.IsNullOrEmpty(a.user_type)).Select(a => a.id).ToArray();
//ids="1,2,3,4,5,6,7";
string ids = string.Join(",", id);

5、左联与内联(例子是DataTable类型)

复制代码
//当on为单条件时;   dt,dt1,dt2都为DataTable类型
//左联比内联,需要多写into,需要多写from gc1 in corr.DefaultIfEmpty(),需要多写corr=gc1。
var results = from student in dt.AsEnumerable()
              join user in dt1.AsEnumerable() on student.Field<int>("student_id") equals user.Field<int>("id")//内联
              join corr in dt2.AsEnumerable() on student.Field<int>("id") equals corr.Field<int?>("studentproject_id") into corr//左联
              from gc1 in corr.DefaultIfEmpty()
              select new
              {
                  student,
                  user,
                  corr = gc1
              };

//当on为多条件时,借助于匿名类型:其实和解决按多条件分组的思路是一样的。
var results = from student in dt.AsEnumerable()
              join zrs in result_zrs on new { districtcounty = student.Field<string>("districtcounty"), school = student.Field<string>("school") }
              equals new { districtcounty = zrs.districtcounty, school = zrs.school } into zrs
              from gc1 in zrs.DefaultIfEmpty()
              select new
              {
                  student,
                  corr = gc1
              };

//取值方式
foreach (var i in results.ToList())
{
    name = i.user.Field<string>("name");
}
复制代码

6、OrderBy排序

//1个排序
list.OrderBy(a => a.student_id);
//2个排序
list.OrderBy(a => a.student_id).ThenBy(a => a.name);
//多个排序
list.OrderBy(a => a.student_id).ThenBy(a => a.name).ThenBy(a => a.sex);

7、随机排序:

复制代码
//方式一
Random rd = new Random(); List<string> liststr = new List<string>(); liststr.Add("aaa"); liststr.Add("bbb"); liststr.Add("ccc"); liststr.Add("111"); liststr.Add("222"); liststr.Add("333"); //随机一个 var s = liststr.OrderBy(_ => Guid.NewGuid()).First(); //随机两个 var ss = liststr.OrderBy(_ => Guid.NewGuid()).Take(2); //乱序 var sss = liststr.OrderBy(o => rd.Next(0, liststr.Count())).ToList();
复制代码
复制代码
//方式二
Random rd = new Random(); list.OrderBy(_=>rd.Next(1,99)).First(); //随机排序通用方法
//就是从原List中每次随机取一项,添加到新的List中,并在原List中删除。这样重复,直到原List为空为止。
//不过要注意,如果要保护原List不受变化,就必须先Copy一份List,再在Copy上进行操作
public static List<T> GetRandomList<T>(List<T> inputList) { //Copy to a array T[] copyArray = new T[inputList.Count]; inputList.CopyTo(copyArray); //Add range List<T> copyList = new List<T>(); copyList.AddRange(copyArray); //Set outputList and random List<T> outputList = new List<T>(); Random rd = new Random(DateTime.Now.Millisecond); while (copyList.Count > 0) { //Select an index and item int rdIndex = rd.Next(0, copyList.Count - 1); T remove = copyList[rdIndex]; //remove it from copyList and add it to output copyList.Remove(remove); outputList.Add(remove); } return outputList; }
复制代码

8、Skip,Take分页

复制代码
//Skip是起始数据,表示从第n+1条数据开始.(此处pageIndex应从0开始)
//pageIndex:页数,pageSize:一页多少条
list = list.Skip(pageIndex * pageSize).Take(pageSize).ToList();
//取前1-10条
list = list.Skip(0).Take(10).ToList();
//取第11-20条
list = list.Skip(10).Take(10).ToList();
//只取10条数据
list = list.Take(10).ToList();
复制代码

9、Distinct去重

//字符串数组
string[] idlist =  new string[ ]{"aaa","bbb","aaa"};
//去除重复aaa
idlist = idlist.Distinct().ToArray();
posted @ 2017-05-31 09:54  你也很优秀  阅读(542)  评论(0)    收藏  举报