11.6.1 使用 group...by 子句进行分组

     class Program
{
static void Main(string[] args)
{
var query = from defect in SampleData.AllDefects
where defect.AssignedTo != null
group defect by defect.AssignedTo; var query2 = SampleData.AllDefects
.Where(defect => defect.AssignedTo != null)
.GroupBy(defect => defect.AssignedTo); foreach (var entry in query)
{
Console.WriteLine(entry.Key.Name);
foreach (var defect in entry)
{
Console.WriteLine(" {0} {1} ", defect.Severity, defect.Summary);
}
Console.WriteLine();
} var query3 = from defect in SampleData.AllDefects
where defect.AssignedTo != null
group defect.Summary by defect.AssignedTo; var query4 = SampleData.AllDefects
.Where(defect => defect.AssignedTo != null)
.GroupBy(defect => defect.AssignedTo,
defect => defect.Summary); foreach (var entry in query3)
{
Console.WriteLine(entry.Key.Name);
foreach (var summary in entry)
{
Console.WriteLine(" {0} ", summary);
}
Console.WriteLine();
} Console.ReadKey();
}
}

11.6.2 查询延续

     class Program
{
static void Main(string[] args)
{
var query = from defect in SampleData.AllDefects
where defect.AssignedTo != null
group defect by defect.AssignedTo into grouped
select new { Assignee = grouped.Key, Count = grouped.Count() }; var query2 = SampleData.AllDefects
.Where(defect => defect.AssignedTo != null)
.GroupBy(defect => defect.AssignedTo)
.Select(grouped => new { Assignee = grouped.Key, Count = grouped.Count() }); foreach (var item in query)
{
Console.WriteLine("{0} {1}", item.Assignee, item.Count);
} Console.WriteLine("======================================"); var query3 = from defect in SampleData.AllDefects
where defect.AssignedTo != null
group defect by defect.AssignedTo into grouped
select new { Assignee = grouped.Key, Count = grouped.Count() } into result
orderby result.Count descending
select result; var query4 = SampleData.AllDefects
.Where(defect => defect.AssignedTo != null)
.GroupBy(defect => defect.AssignedTo)
.Select(grouped => new { Assignee = grouped.Key, Count = grouped.Count() })
.OrderByDescending(result => result.Count); foreach (var item in query3)
{
Console.WriteLine("{0} {1}", item.Assignee, item.Count);
} Console.ReadKey();
}
}

join ... into 不是延续 你很容易掉进这样的陷阱,即看到了上下文关键字 into ,就认为这是查询延续。
对于连接来说,这是不对的。用于分组连接的 join ... into 子句不能形成一个延续的结构。
主要的区别在于,在分组连接中,你仍然可以使用所有的早期范围变量(用于连接右边名称的范围变量除外)。
而对比本节的查询不难发现,延续会清除之前的范围变量,只有在延续中声明的范围变量才能在供后续使用。

SampleData代码,如下

     public class SampleData
{
static List<Defect> defects;
static List<User> users;
static List<Project> projects;
static List<NotificationSubscription> subscriptions; public static readonly DateTime Start = May();
public static readonly DateTime End = May(); public static IEnumerable<Defect> AllDefects
{
get { return defects; }
} public static IEnumerable<User> AllUsers
{
get { return users; }
} public static IEnumerable<Project> AllProjects
{
get { return projects; }
} public static IEnumerable<NotificationSubscription> AllSubscriptions
{
get { return subscriptions; }
} public static class Projects
{
public static readonly Project SkeetyMediaPlayer = new Project { Name = "Skeety Media Player" };
public static readonly Project SkeetyTalk = new Project { Name = "Skeety Talk" };
public static readonly Project SkeetyOffice = new Project { Name = "Skeety Office" };
} public static class Users
{
public static readonly User TesterTim = new User("Tim Trotter", UserType.Tester);
public static readonly User TesterTara = new User("Tara Tutu", UserType.Tester);
public static readonly User DeveloperDeborah = new User("Deborah Denton", UserType.Developer);
public static readonly User DeveloperDarren = new User("Darren Dahlia", UserType.Developer);
public static readonly User ManagerMary = new User("Mary Malcop", UserType.Manager);
public static readonly User CustomerColin = new User("Colin Carton", UserType.Customer);
} static SampleData()
{
projects = new List<Project>
{
Projects.SkeetyMediaPlayer,
Projects.SkeetyTalk,
Projects.SkeetyOffice
}; users = new List<User>
{
Users.TesterTim,
Users.TesterTara,
Users.DeveloperDeborah,
Users.DeveloperDarren,
Users.ManagerMary,
Users.CustomerColin
}; subscriptions = new List<NotificationSubscription>
{
new NotificationSubscription { Project=Projects.SkeetyMediaPlayer, EmailAddress="media-bugs@skeetysoft.com" },
new NotificationSubscription { Project=Projects.SkeetyTalk, EmailAddress="talk-bugs@skeetysoft.com" },
new NotificationSubscription { Project=Projects.SkeetyOffice, EmailAddress="office-bugs@skeetysoft.com" },
new NotificationSubscription { Project=Projects.SkeetyMediaPlayer, EmailAddress="theboss@skeetysoft.com"}
}; defects = new List<Defect>
{
new Defect
{
Project = Projects.SkeetyMediaPlayer,
Created = May(),
CreatedBy = Users.TesterTim,
Summary = "MP3 files crash system",
Severity = Severity.Showstopper,
AssignedTo = Users.DeveloperDarren,
Status = Status.Accepted,
LastModified = May()
}, new Defect
{
Project = Projects.SkeetyMediaPlayer,
Created = May(),
CreatedBy = Users.DeveloperDeborah,
Summary = "Text is too big",
Severity = Severity.Trivial,
AssignedTo = null,
Status = Status.Closed,
LastModified = May()
}, new Defect
{
Project = Projects.SkeetyTalk,
Created = May(),
CreatedBy = Users.CustomerColin,
Summary = "Sky is wrong shade of blue",
Severity = Severity.Minor,
AssignedTo = Users.TesterTara,
Status = Status.Fixed,
LastModified = May()
}, new Defect
{
Project = Projects.SkeetyMediaPlayer,
Created = May(),
CreatedBy = Users.DeveloperDarren,
Summary = "Can't play files more than 200 bytes long",
Severity = Severity.Major,
AssignedTo = Users.DeveloperDarren,
Status = Status.Reopened,
LastModified = May()
}, new Defect
{
Project = Projects.SkeetyMediaPlayer,
Created = May(),
CreatedBy = Users.TesterTim,
Summary = "Installation is slow",
Severity = Severity.Trivial,
AssignedTo = Users.TesterTim,
Status = Status.Fixed,
LastModified = May()
}, new Defect
{
Project = Projects.SkeetyMediaPlayer,
Created = May(),
CreatedBy = Users.ManagerMary,
Summary = "DivX is choppy on Pentium 100",
Severity = Severity.Major,
AssignedTo = Users.DeveloperDarren,
Status = Status.Accepted,
LastModified = May()
}, new Defect
{
Project = Projects.SkeetyTalk,
Created = May(),
CreatedBy = Users.DeveloperDeborah,
Summary = "Client acts as virus",
Severity = Severity.Showstopper,
AssignedTo = null,
Status = Status.Closed,
LastModified = May()
}, new Defect
{
Project = Projects.SkeetyMediaPlayer,
Created = May(),
CreatedBy = Users.DeveloperDarren,
Summary = "Subtitles only work in Welsh",
Severity = Severity.Major,
AssignedTo = Users.TesterTim,
Status = Status.Fixed,
LastModified = May()
}, new Defect
{
Project = Projects.SkeetyTalk,
Created = May(),
CreatedBy = Users.CustomerColin,
Summary = "Voice recognition is confused by background noise",
Severity = Severity.Minor,
AssignedTo = null,
Status = Status.Closed,
LastModified = May()
}, new Defect
{
Project = Projects.SkeetyTalk,
Created = May(),
CreatedBy = Users.TesterTim,
Summary = "User interface should be more caramelly",
Severity = Severity.Trivial,
AssignedTo = Users.DeveloperDarren,
Status = Status.Created,
LastModified = May()
}, new Defect
{
Project = Projects.SkeetyMediaPlayer,
Created = May(),
CreatedBy = Users.ManagerMary,
Summary = "Burning a CD makes the printer catch fire",
Severity = Severity.Showstopper,
AssignedTo = null,
Status = Status.Closed,
LastModified = May()
}, new Defect
{
Project = Projects.SkeetyTalk,
Created = May(),
CreatedBy = Users.TesterTara,
Summary = "Peer to peer pairing passes parameters poorly",
Severity = Severity.Minor,
AssignedTo = Users.DeveloperDarren,
Status = Status.Accepted,
LastModified = May()
}, new Defect
{
Project = Projects.SkeetyTalk,
Created = May(),
CreatedBy = Users.DeveloperDarren,
Summary = "Delay when sending message",
Severity = Severity.Minor,
AssignedTo = Users.TesterTara,
Status = Status.Fixed,
LastModified = May()
}, new Defect
{
Project = Projects.SkeetyMediaPlayer,
Created = May(),
CreatedBy = Users.ManagerMary,
Summary = "Volume control needs to go to 11",
Severity = Severity.Minor,
AssignedTo = Users.DeveloperDarren,
Status = Status.Created,
LastModified = May()
}, new Defect
{
Project = Projects.SkeetyMediaPlayer,
Created = May(),
CreatedBy = Users.CustomerColin,
Summary = "Splash screen fades too quickly",
Severity = Severity.Minor,
AssignedTo = Users.TesterTara,
Status = Status.Fixed,
LastModified = May()
}, new Defect
{
Project = Projects.SkeetyTalk,
Created = May(),
CreatedBy = Users.DeveloperDeborah,
Summary = "Text box doesn't keep up with fast typing",
Severity = Severity.Major,
AssignedTo = Users.DeveloperDeborah,
Status = Status.Accepted,
LastModified = May()
}, new Defect
{
Project = Projects.SkeetyTalk,
Created = May(),
CreatedBy = Users.DeveloperDarren,
Summary = "Password displayed in plain text",
Severity = Severity.Showstopper,
AssignedTo = null,
Status = Status.Closed,
LastModified = May()
}, new Defect
{
Project = Projects.SkeetyMediaPlayer,
Created = May(),
CreatedBy = Users.TesterTim,
Summary = "Play button points the wrong way",
Severity = Severity.Major,
AssignedTo = Users.TesterTim,
Status = Status.Fixed,
LastModified = May()
}, new Defect
{
Project = Projects.SkeetyMediaPlayer,
Created = May(),
CreatedBy = Users.CustomerColin,
Summary = "Wizard needed for CD burning",
Severity = Severity.Minor,
AssignedTo = Users.CustomerColin,
Status = Status.Fixed,
LastModified = May()
}, new Defect
{
Project = Projects.SkeetyMediaPlayer,
Created = May(),
CreatedBy = Users.ManagerMary,
Summary = "Subtitles don't display during fast forward",
Severity = Severity.Trivial,
AssignedTo = Users.DeveloperDarren,
Status = Status.Accepted,
LastModified = May()
}, new Defect
{
Project = Projects.SkeetyMediaPlayer,
Created = May(),
CreatedBy = Users.DeveloperDarren,
Summary = "Memory leak when watching Memento",
Severity = Severity.Trivial,
AssignedTo = Users.DeveloperDeborah,
Status = Status.Created,
LastModified = May()
}, new Defect
{
Project = Projects.SkeetyTalk,
Created = May(),
CreatedBy = Users.DeveloperDeborah,
Summary = "Profile screen shows login count of -1",
Severity = Severity.Major,
AssignedTo = Users.DeveloperDeborah,
Status = Status.Accepted,
LastModified = May()
}, new Defect
{
Project = Projects.SkeetyTalk,
Created = May(),
CreatedBy = Users.TesterTim,
Summary = "Server crashes under heavy load (3 users)",
Severity = Severity.Major,
AssignedTo = Users.DeveloperDeborah,
Status = Status.Accepted,
LastModified = May()
}, new Defect
{
Project = Projects.SkeetyMediaPlayer,
Created = May(),
CreatedBy = Users.TesterTara,
Summary = "Unable to connect to any media server",
Severity = Severity.Showstopper,
AssignedTo = Users.DeveloperDarren,
Status = Status.Reopened,
LastModified = May()
}, new Defect
{
Project = Projects.SkeetyMediaPlayer,
Created = May(),
CreatedBy = Users.DeveloperDeborah,
Summary = "UI turns black and white when playing old films",
Severity = Severity.Minor,
AssignedTo = Users.TesterTara,
Status = Status.Fixed,
LastModified = May()
}, new Defect
{
Project = Projects.SkeetyTalk,
Created = May(),
CreatedBy = Users.ManagerMary,
Summary = "Password reset changes passwords for all users",
Severity = Severity.Showstopper,
AssignedTo = null,
Status = Status.Closed,
LastModified = May()
}, new Defect
{
Project = Projects.SkeetyMediaPlayer,
Created = May(),
CreatedBy = Users.TesterTim,
Summary = "Modern music sounds rubbish",
Severity = Severity.Trivial,
AssignedTo = Users.DeveloperDarren,
Status = Status.Created,
LastModified = May()
}, new Defect
{
Project = Projects.SkeetyTalk,
Created = May(),
CreatedBy = Users.TesterTim,
Summary = "Webcam makes me look bald",
Severity = Severity.Showstopper,
AssignedTo = Users.TesterTim,
Status = Status.Fixed,
LastModified = May()
}, new Defect
{
Project = Projects.SkeetyTalk,
Created = May(),
CreatedBy = Users.CustomerColin,
Summary = "Sound is distorted when speakers are underwater",
Severity = Severity.Major,
AssignedTo = Users.DeveloperDarren,
Status = Status.Created,
LastModified = May()
}, new Defect
{
Project = Projects.SkeetyTalk,
Created = May(),
CreatedBy = Users.DeveloperDarren,
Summary = "Japanese characters don't display properly",
Severity = Severity.Major,
AssignedTo = Users.DeveloperDeborah,
Status = Status.Accepted,
LastModified = May()
}, new Defect
{
Project = Projects.SkeetyMediaPlayer,
Created = May(),
CreatedBy = Users.TesterTara,
Summary = "Video takes 100% of CPU",
Severity = Severity.Major,
AssignedTo = Users.DeveloperDeborah,
Status = Status.Accepted,
LastModified = May()
}, new Defect
{
Project = Projects.SkeetyMediaPlayer,
Created = May(),
CreatedBy = Users.TesterTim,
Summary = "DVD Easter eggs unavailable",
Severity = Severity.Trivial,
AssignedTo = Users.DeveloperDarren,
Status = Status.Created,
LastModified = May()
}, new Defect
{
Project = Projects.SkeetyTalk,
Created = May(),
CreatedBy = Users.ManagerMary,
Summary = "Transparency is high for menus to be readable",
Severity = Severity.Minor,
AssignedTo = Users.DeveloperDeborah,
Status = Status.Accepted,
LastModified = May()
}, new Defect
{
Project = Projects.SkeetyMediaPlayer,
Created = May(),
CreatedBy = Users.CustomerColin,
Summary = "About box is missing version number",
Severity = Severity.Minor,
AssignedTo = Users.CustomerColin,
Status = Status.Fixed,
LastModified = May()
}, new Defect
{
Project = Projects.SkeetyTalk,
Created = May(),
CreatedBy = Users.TesterTim,
Summary = "Logs record confidential conversations",
Severity = Severity.Major,
AssignedTo = Users.DeveloperDarren,
Status = Status.Reopened,
LastModified = May()
}, new Defect
{
Project = Projects.SkeetyTalk,
Created = May(),
CreatedBy = Users.DeveloperDeborah,
Summary = "Profanity filter is too aggressive",
Severity = Severity.Minor,
AssignedTo = Users.TesterTara,
Status = Status.Fixed,
LastModified = May()
}, new Defect
{
Project = Projects.SkeetyMediaPlayer,
Created = May(),
CreatedBy = Users.TesterTara,
Summary = "Full screen mode fails on dual monitors",
Severity = Severity.Minor,
AssignedTo = Users.DeveloperDeborah,
Status = Status.Created,
LastModified = May()
}, new Defect
{
Project = Projects.SkeetyMediaPlayer,
Created = May(),
CreatedBy = Users.CustomerColin,
Summary = "Visualization hypnotises pets",
Severity = Severity.Minor,
AssignedTo = Users.DeveloperDeborah,
Status = Status.Accepted,
LastModified = May()
}, new Defect
{
Project = Projects.SkeetyTalk,
Created = May(),
CreatedBy = Users.ManagerMary,
Summary = "Resizing while typing loses input",
Severity = Severity.Trivial,
AssignedTo = Users.DeveloperDarren,
Status = Status.Created,
LastModified = May()
}, new Defect
{
Project = Projects.SkeetyMediaPlayer,
Created = May(),
CreatedBy = Users.TesterTim,
Summary = "Network is saturated when playing WAV file",
Severity = Severity.Minor,
AssignedTo = Users.TesterTim,
Status = Status.Fixed,
LastModified = May()
}, new Defect
{
Project = Projects.SkeetyMediaPlayer,
Created = May(),
CreatedBy = Users.TesterTara,
Summary = "Media library tells user to keep the noise down",
Severity = Severity.Major,
AssignedTo = Users.DeveloperDarren,
Status = Status.Created,
LastModified = May()
}
};
} public static DateTime May(int day)
{
return new DateTime(, , day);
} }
public enum UserType : byte
{
Customer,
Developer,
Tester,
Manager,
}
public class Defect
{
public Project Project { get; set; }
/// <summary>
/// Which user is this defect currently assigned to? Should not be null until the status is Closed.
/// </summary>
public User AssignedTo { get; set; }
public string Summary { get; set; }
public Severity Severity { get; set; }
public Status Status { get; set; }
public DateTime Created { get; set; }
public DateTime LastModified { get; set; }
public User CreatedBy { get; set; }
public int ID { get; private set; } public Defect()
{
ID = StaticCounter.Next();
} public override string ToString()
{
return string.Format("{0,2}: {1}\r\n ({2:d}-{3:d}, {4}/{5}, {6} -> {7})",
ID, Summary, Created, LastModified, Severity, Status, CreatedBy.Name,
AssignedTo == null ? "n/a" : AssignedTo.Name);
}
}
public class NotificationSubscription
{
/// <summary>
/// Project for which this subscriber is notified
/// </summary>
public Project Project { get; set; } /// <summary>
/// The address to send the notification to
/// </summary>
public string EmailAddress { get; set; }
}
public class Project
{
public string Name { get; set; } public override string ToString()
{
return string.Format("Project: {0}", Name);
}
}
public enum Severity : byte
{
Trivial,
Minor,
Major,
Showstopper,
}
public static class StaticCounter
{
static int next = ;
public static int Next()
{
return next++;
}
}
public enum Status : byte
{
/// <summary>
/// Defect has been opened, but not verified as reproducible or an issue.
/// </summary>
Created,
/// <summary>
/// Defect has been verified as an issue requiring work.
/// </summary>
Accepted,
/// <summary>
/// Defect has been fixed in code, but not verified other than through developer testing.
/// </summary>
Fixed,
/// <summary>
/// Defect was fixed, but has now been reopened due to failing verification.
/// </summary>
Reopened,
/// <summary>
/// Defect has been fixed and tested; the fix is satisfactory.
/// </summary>
Closed,
}
public class User
{
public string Name { get; set; }
public UserType UserType { get; set; } public User(string name, UserType userType)
{
Name = name;
UserType = userType;
} public override string ToString()
{
return string.Format("User: {0} ({1})", Name, UserType);
}
}
static class Extensions
{
public static Dummy<T> Where<T>(this Dummy<T> dummy,
Func<T, bool> predicate)
{
Console.WriteLine("Where called");
return dummy;
}
}
class Dummy<T>
{
public Dummy<U> Select<U>(Func<T, U> selector)
{
Console.WriteLine("Select called");
return new Dummy<U>();
}
}
public class DateTimeRange : IEnumerable<DateTime>
{
private readonly DateTime start;
private readonly DateTime end; public DateTimeRange(DateTime start, DateTime end)
{
this.start = start;
this.end = end;
} public IEnumerator<DateTime> GetEnumerator()
{
for (DateTime current = start; current <= end; current = current.AddDays())
{
yield return current;
}
} IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}

11.6 【Linq】分组和延续的更多相关文章

  1. Linq分组功能

    Linq在集合操作上很方便,很多语法都借鉴自sql,但linq的分组却与sql有一定的区别,故整理发布如下. 1.  Linq分组 分组后以Key属性访问分组键值. 每一组为一个IEnumberAbl ...

  2. Linq分组操作之GroupBy,GroupJoin扩展方法源码分析

    Linq分组操作之GroupBy,GroupJoin扩展方法源码分析 一. GroupBy 解释: 根据指定的键选择器函数对序列中的元素进行分组,并且从每个组及其键中创建结果值. 查询表达式: var ...

  3. Linq分组,linq方法分组

    Group在SQL经常使用,通常是对一个字段或者多个字段分组,求其总和,均值等. Linq中的Groupby方法也有这种功能.具体实现看代码: 假设有如下的一个数据集: 01.public class ...

  4. Linq分组查询统计

    这里介绍Linq使用Group By和Count得到每个CategoryID中产品的数量,Linq使用Group By和Count得到每个CategoryID中断货产品的数量等方面. 学经常会遇到Li ...

  5. C# 泛型分组和Linq分组的异同

    没什么好说的,因为用的到,所以作个记录, 代码如下: using System; using System.Collections.Generic; using System.Linq; using ...

  6. C#高级编程9 第11章 Linq

    Linq 1.Linq概述 列表和实体 准备数据: public class Championship { public int Year { get; set; } public string Fi ...

  7. c# linq 分组groupby

    转载: https://www.cnblogs.com/cncc/p/9846390.html 一.先准备要使用的类: 1.Person类: class Person { public string ...

  8. C#高级编程(第9版) 第11章 LINQ 笔记

    概述语言集成查询(Language Integrated Query, LINQ)在C#编程语言中集成了查询语法,可以用相同的语法访问不同的数据源.LINQ提供了不同数据源的抽象层,所以可以使用相同的 ...

  9. 11、Linq的使用

    一.种类 1.Linq to Objects,实现了IEnumerable<T>集合对象的集成查询 2.Linq to sql,针对关系数据库MSSQL的解释查询 3.Linq to En ...

随机推荐

  1. spring mvc之applicationContext

    1.ApplicationContext是在package org.springframework.context下,是spring的,spring context包下的. applicationCo ...

  2. php 数组 array()

    定义和用法 array() 创建数组,带有键和值.如果在创建数组时省略了键,则生成一个整数键,默认从 0 开始,然后以 1 进行递增. 用 array() 创建一个数组,可使用 => 来分隔键和 ...

  3. Spring 定时器 No qualifying bean of type [org.springframework.scheduling.TaskScheduler] is defined

    Spring 定时器 No qualifying bean of type [org.springframework.scheduling.TaskScheduler] is defined stac ...

  4. java 工厂方法模式简单实例

    工厂方法模式:也叫工厂模式,属于类创建型模式,工厂父类(接口)负责定义产品对象的公共接口,而子类工厂则负责创建具体的产品对象. 目的:是为了把产品的实例化操作延迟到子类工厂中完成,通过工厂子类来决定究 ...

  5. curl强制下载文件

    <?phpfunction download_remote_file_with_curl($file_url, $save_to) { $ch = curl_init(); curl_setop ...

  6. ride关键字

    定义变量:set variable 打印 :log 列表:create list 字符转数字型:evaluate 随机数:evaluate random.randint 日志截图:先导入screens ...

  7. Python27天 反射 ,isinstance与ssubclass 内置方法

    所学内容 反射 1.hasattr ( 判断一个属性在对象里有没有 ) -------------------- [对象,字符串属性]本质是:# 判断 ' name ' in obj.__dict__ ...

  8. 35个jquery小技巧

    1. 禁止右键点击 ? 1 2 3 4 5 $(document).ready(function(){     $(document).bind("contextmenu",fun ...

  9. SQLServer2008 将本地excel导入到远程服务器表

    --1.创建链接服务器,相当于创建一个访问远程数据库的快捷方式 exec sp_addlinkedserver 'TestLink', ' ', 'SQLOLEDB ', '111.11.1.111' ...

  10. DeltaFish 校园物资共享平台 第一次小组会议

    软工小组第一次会议 会议地点:图书馆 会议时间:19:00 ~ 20:00 与会人员:软工小组全体成员 请假人员:无缺席人员:无 记录人:陈志锴 整理人:曾子轩 会议记录 一.确认选题 每一位成员提出 ...