/// <summary>
/// Linq to object(数组、集合)--内存里面的数据
/// Linq to sql(查询数据库用的)--在数据库数据
/// Linq XML查询XML文件
/// </summary>
List<Students> studentsList = new List<Students>()
{
new Students
{
Id=1,
Name="喜刷刷",
ClassId=2,
Age=22
},
new Students
{
Id=2,
Name="喜刷刷2",
ClassId=2,
Age=22
},
new Students
{
Id=3,
Name="喜刷刷3",
ClassId=2,
Age=22
},
new Students
{
Id=4,
Name="喜刷刷4",
ClassId=2,
Age=22
},
new Students
{
Id=5,
Name="喜刷刷3",
ClassId=2,
Age=22
}
};
List<StuClass> stuClasses = new List<StuClass>
{
new StuClass
{
ID=1,
Name="111"
},
new StuClass
{
ID=2,
Name="222"
},
new StuClass
{
ID=3,
Name="333"
},
new StuClass
{
ID=4,
Name="444"
}
};
public void Show()
{
List<Students> list = new List<Students>();
#region
foreach (var item in studentsList)
{
if (item.ClassId == 2)
{
list.Add(item);
}
}
//自定义Linq
list = AntWhere(studentsList, s => s.Age < 23);
//官方Linq
var list4 = studentsList.Where(s => s.Age < 23);
//自定义扩展Linq
var list7 = studentsList.AntWhere(s => s.Age < 23);
//表达式方法(匿名类)将查询的结果一新的匿名类返回
//select映射返回一个新的对象
var list5 = from s in studentsList
where s.Age == 22
select new
{
Name = s.Name
};
//连表查询,将查询接过返回一个新的对象
var list9 = from s in studentsList
join c in stuClasses on s.ClassId equals c.ID//equals 替代等号
select new
{
ID = s.Id,
Name = c.Name
};
var list6 = studentsList.Join(stuClasses, s => s.ClassId, c => c.ID, (s, c) => new
{
ID = s.Id,
Name = c.Name
});
var list8 = studentsList.Select(s => s);
#endregion
//EF框架简单使用
OAEntities db = new OAEntities();
var userInfoList = db.UserInfo.Where(s => s.ID > 1);
foreach (var item in userInfoList)
{
Console.WriteLine(item.Remark);
}
}
/// <summary>
/// Func<Students,bool> Students委托形参,bool委托返回值类型
/// </summary>
/// <param name="resource"></param>
/// <param name="where"></param>
/// <returns></returns>
public List<Students>AntWhere(List<Students> resource,Func<Students,bool>where)
{
List<Students> list = new List<Students>();
foreach (var item in resource)
{
if (where.Invoke(item))
{
list.Add(item);
}
}
return list;
}
}
/// <summary>
/// 自定义扩展Linq方法
/// </summary>
public static class LinqExtend
{
public static IEnumerable<T> AntWhere<T>(this IEnumerable<T> resource, Func<T, bool> where)
{
List<T> list = new List<T>();
foreach (var item in resource)
{
if (where.Invoke(item))
{
list.Add(item);
}
}
return list;
}
}
c# Linq 及其扩展方法的使用
于 2023-11-21 17:26:28 首次发布