Linq入门演练---(1)基本用法-分组,排序,内连接
这一节大家共同学习下LINQ的基本用法,主要包括LINQ的分组,排序,和内外连接。
1.分组
基本语法: group element by key
element 表示查询结果返回的元素,key表示分组条件。group子句返回的类型为IGrouping<TKey,TElement>的查询结果。
IGrouping<TKey,TElement>可以看成一个hashtable内部嵌套一个list列表的数据结果. 其中TElement就是一个list
我们看下面的一个事例,下面这个实例演示根据性别对用户进行分组
代码
[csharp]
public class User
{
public User(string userName,string 易做图,int age)
{
UserName = userName;
Sex = 易做图;
Age = age;
}
public string UserName
{
get;
set;
}
public string Sex
{
get;
set;
}
public int Age
{
get;
set;
}
}
public class User
{
public User(string userName,string 易做图,int age)
{
UserName = userName;
Sex = 易做图;
Age = age;
}
public string UserName
{
get;
set;
}
public string Sex
{
get;
set;
}
public int Age
{
get;
set;
}
}
[csharp]
private void button1_Click(object sender, EventArgs e)
{
User[] users = {
new User("刘德华","男",40),
new User("张学友","男",30),
new User("张曼玉","女",35),
new User("杨幂","女",53)
};
var query1 =
from var1 in users
group var1 by var1.Sex;
string str = "";
foreach (var item in query1)
{
str += item.Key + "\r\n";
foreach (var user in item)
{
str += user.UserName + "--" + user.Sex + "--" + user.Age.ToString() + "\r\n";
}
}
textBox1.Text = str;
}
private void button1_Click(object sender, EventArgs e)
{
User[] users = {
new User("刘德华","男",40),
new User("张学友","男",30),
new User("张曼玉","女",35),
&
补充:软件开发 , C# ,