首页 > 代码库 > 使用 Linq 对多个对象进行join操作 C#

使用 Linq 对多个对象进行join操作 C#

     class A {
            public int id { get; set; }
            public string name { get; set; }
        }
        class B {
            public int id { get; set; }
            public int age { get; set; }
        }
        class C {
            public int id { get; set; }
            public string address { get; set; }
        }


        private void button8_Click(object sender, EventArgs e)
        {
            List<A> ListA = new List<A>();
            List<B> ListB = new List<B>();
            List<C> ListC = new List<C>();
            for (int i = 0; i < 10; i++)
            {
                ListA.Add(new A() { id = i, name = "name" + i.ToString() });
                ListB.Add(new B() { id = i, age = 20 + i });
                ListC.Add(new C() { id = i, address = "地址" + i.ToString() });
            }


            var kk = from a in ListA
                     join b in ListB on a.id equals b.id //join操作
                     join c in ListC on a.id equals c.id //join操作
                     where a.name.IndexOf("name") >= 0  // where操作
                     select new
                     {       //重新组织列
                         id = a.id,
                         name = a.name,
                         age = b.age,
                         address = c.address
                     };
            StringBuilder sb = new StringBuilder();
            foreach (var o in kk)
            {
                sb.Append( o.id + " " + o.name + " "  +  o.age + " " + o.address + "\n");
            }
            richTextBox1.Text = sb.ToString();
        }

 

使用 Linq 对多个对象进行join操作 C#