4. 联结操作符—【LINQ标准查询操作符】

public class Join_LINQ
    {
        static  string ContextString = System.Configuration.ConfigurationSettings.AppSettings["ContextString"].ToString();
        static DataContext context = new DataContext(ContextString);
        static Table<Contact> contact = context.GetTable<Contact>();
        static Table<Employee> emp = context.GetTable<Employee>();

        #region Join
        public static void Print_Join()
        {
            var joinQuery = from c in contact
                            join e in emp on c.ContactID equals e.ContactID
                            where c.FirstName.StartsWith("R")
                            orderby c.LastName
                            select new { e.EmployeeID, c.FirstName, c.LastName, c.EmailAddress, e.Title, e.HireDate };
            // 方法语法
            var joinMethodQuery = contact.Join(emp, c => c.ContactID, e => e.ContactID, (c, e) => new { e.EmployeeID, c.FirstName, c.LastName, c.EmailAddress, e.Title, e.HireDate }).Where(c => c.FirstName.StartsWith("R")).OrderBy(c => c.LastName);

            foreach (var item in joinQuery.Take(3))
            {
                Console.WriteLine(item);
            }

            Console.ReadKey();
        }
        #endregion

        #region GroupJoin
        public static void Print_GroupJoin()
        {
            List<Foods> foods = new List<Foods> { new Foods { Kind = "Meat" }, new Foods { Kind = "Fruit" }, new Foods { Kind = "Drink" } };
            List<Food> food = new List<Food> { 
                        new Food{Name= "Beef",FoodKind="Meat"},
                        new Food{Name = "Chicken",FoodKind = "Meat"},
                        new Food{Name = "Apple",FoodKind = "Fruit"},
                        new Food{Name = "Pear",FoodKind = "Fruit"},
                        new Food{Name = "Coca Cola",FoodKind = "Drink"},
                        new Food{Name = "OX",FoodKind = "Drink"},
                        new Food{Name = "Beer",FoodKind = "Drink"},
            };

            var groupJoinQuery = foods.GroupJoin(food, fs => fs.Kind, f => f.FoodKind, (fs, f) => new { FoodKind = fs.Kind, FoodName = f.Select(o => o.Name) });

            foreach (var item in groupJoinQuery)
            {
                Console.WriteLine(item.FoodKind);
                foreach (var i in item.FoodName)
                {
                    Console.WriteLine(" " + i.ToString());
                }                
            }

            Console.ReadKey();
        }
        #endregion
    }

    public struct Foods
    {
        public string Kind;
    }

    public struct Food
    {
        public string Name;
        public string FoodKind;
    }
posted @ 2010-04-17 21:26  CityWalker  阅读(240)  评论(0编辑  收藏  举报
天天来