linq to sql 连接分组使用join和into

    技术2025-11-12  12

    先附上源代码再说明吧:

     

    源代码如下:

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; namespace consoleTest2 { class Transport { public string Name { get; set; } public string How { get; set; } public Transport(string n, string h) { Name = n; How = h; } } class vehicle { public string vehicleName { get; set; } public string vehicleHow { get; set; } public vehicle(string n, string h) { vehicleName = n; vehicleHow = h; } } class Program { static void Main(string[] args) { vehicle[] vehicles = { new vehicle("a","Land"), new vehicle("b","Air"), new vehicle("c","Sea"), new vehicle("d","Air"), new vehicle("e","Sea"), new vehicle("f","Land"), new vehicle("g","Sea"), new vehicle("g","Sea"), new vehicle("g","Sea"), new vehicle("g","Sea"), }; // An array of transports. Transport[] transports = { new Transport("Bicycle", "Land"), new Transport("Balloon", "Air"), new Transport("Boat", "Sea"), new Transport("Jet", "Air"), new Transport("Canoe", "Sea"), new Transport("Biplane", "Air"), new Transport("Car", "Land"), new Transport("Cargo Ship", "Sea"), new Transport("Train", "Land") }; // Create a query that uses a group join to produce // a list of item names and IDs organized by category. var byHow = from how in vehicles join trans in transports on how.vehicleHow equals trans.How into lst select new { How=how, Tlist = lst };总共创建了10个对象。根据上面的对象数组(vehicle)来进行的。 // Execute the query and display the results. int count = 0; foreach (var t in byHow) { Console.WriteLine("the type of transports{0}", t.How.vehicleName); count++; foreach(var r in t.Tlist) { Console.WriteLine(r.How+" "+r.Name); } } Console.WriteLine(count); } } }  

     

     

     var byHow = from how in  vehicles

                            join trans in transports

                            on how.vehicleHow equals trans.How

                            into lst                                           //    此lst是IEnumerable<transport> 类型

                            select new { How=how, Tlist = lst };

       注意:在select以前的代码,lst 代表的是经过筛选后匹配的实例,一般是一个枚举类型,这时两数据源并没有合并在一起,

               还只是分开。若要选择具体显示的字段时,可以在select执行new操作。确定刷选的字符。

     

     

    此句的运行原理为:1:从vehicles取出每一个对象,再将每一个对象how与transports中how进行匹配,此时一个vehicles可能匹配多个transports对象,也就是一对多的关系。如果vehicles有10个对象,那么将进行10次的匹配,不管vehicles中对象的字段是否有相同的值。都会进行一一的匹配。

    最新回复(0)