LINQ Query using Multiple From and Multiple Collections
Posted
on Microsoft .NET Support Team
See other posts from Microsoft .NET Support Team
Published on Tue, 22 Dec 2009 13:38:00 +0000
Indexed on
2010/03/16
15:31 UTC
Read the original article
Hit count: 809
.NET Framework 3.5
|LinqToSQL
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Text;
5:
6: namespace ConsoleApplication2
7: {
8: class Program
9: {
10: static void Main(string[] args)
11: {
12: var emps = GetEmployees();
13: var deps = GetDepartments();
14:
15: var results = from e in emps
16: from d in deps
17: where e.EmpNo >= 1 && d.DeptNo <= 30
18: select new { Emp = e, Dept = d };
19:
20: foreach (var item in results)
21: {
22: Console.WriteLine("{0},{1},{2},{3}", item.Dept.DeptNo, item.Dept.DName, item.Emp.EmpNo, item.Emp.EmpName);
23: }
24: }
25:
26: private static List<Emp> GetEmployees()
27: {
28: return new List<Emp>() {
29: new Emp() { EmpNo = 1, EmpName = "Smith", DeptNo = 10 },
30: new Emp() { EmpNo = 2, EmpName = "Narayan", DeptNo = 20 },
31: new Emp() { EmpNo = 3, EmpName = "Rishi", DeptNo = 30 },
32: new Emp() { EmpNo = 4, EmpName = "Guru", DeptNo = 10 },
33: new Emp() { EmpNo = 5, EmpName = "Priya", DeptNo = 20 },
34: new Emp() { EmpNo = 6, EmpName = "Riya", DeptNo = 10 }
35: };
36: }
37:
38: private static List<Department> GetDepartments()
39: {
40: return new List<Department>() {
41: new Department() { DeptNo=10, DName="Accounts" },
42: new Department() { DeptNo=20, DName="Finance" },
43: new Department() { DeptNo=30, DName="Travel" }
44: };
45: }
46: }
47:
48: class Emp
49: {
50: public int EmpNo { get; set; }
51: public string EmpName { get; set; }
52: public int DeptNo { get; set; }
53: }
54:
55: class Department
56: {
57: public int DeptNo { get; set; }
58: public String DName { get; set; }
59: }
60: }
© Microsoft .NET Support Team or respective owner