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. OpenCV使用说明

    我在这边大概说一下OpenCV的使用,具体环境配置参考下面我给出的两个链接. 1. 对于目前OpenCV来说,安装变的简单了很多,现在官方已经给出了预编译文件,不要重新编译.具体使用可以参考http: ...

  2. hdu 1010 Tempter of the Bone (奇偶性剪枝)

    题意:有一副二维地图'S'为起点,'D'为终点,'.'是可以行走的,'X'是不能行走的.问能否只走T步从S走到D? 题解:最容易想到的就是DFS暴力搜索,,但是会超时...=_=... 所以,,要有其 ...

  3. hdu 4850 字符串构造---欧拉回路构造序列 递归+非递归实现

    http://acm.hdu.edu.cn/showproblem.php? pid=4850 题意:构造长度为n的字符序列.使得>=4的子串仅仅出现一次 事实上最长仅仅能构造出来26^4+4- ...

  4. zoj 1648 Circuit Board

    题目:意思就是推断给定的几条线段是否有相交的. 方法:模版吧,有空在来细细学习. 代码: #include <iostream> #include <cstdio> using ...

  5. wesome-android

    awesome-android Introduction android libs from github System requirements Android Notice If the lib ...

  6. 深入理解android view 生命周期

    作为自定义 view 的基础,如果不了解Android  view 的生命周期 , 那么你将会在后期的维护中发现这样那样的问题 ....... 做过一段时间android 开发的同学都知道,一般 on ...

  7. jdbc数据库中的增删改

    HttpSession session=request.getSession(); session.setAttribute("currentUser",u.username);/ ...

  8. getField();在TP5里成什么了?

    拆分为value和column了 $comps=db("company")->where(array("areaid"=>$areaid))-> ...

  9. NYOJ999 师傅又被妖怪抓走了

    只记得当下的眼疼 , ok 各种数据也试了 , 就是 他娘的不对 , 我也是醉了 . 也是日了最野的狗 附上日了哮天犬的代码 , 这个题 先放放, 一段时间后再试试 , 明天开始状态压缩吧 .为期两天 ...

  10. POJ 2945 trie树

    Find the Clones Time Limit: 5000MS Memory Limit: 65536K Total Submissions: 7704 Accepted: 2879 Descr ...