如何将不同的列合并为不同表中的单个列

时间:2014-11-08 13:46:40

标签: c# asp.net sql-server-2008

http://i.stack.imgur.com/vBQno.jpg

我正在努力将个人教师的时间表整合到一个主时间表中。

1 个答案:

答案 0 :(得分:1)

您可以使用lambda或LINQ来完成此任务。我提供了一个工作实例。

namespace ConsoleApplication1
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    class Program
    {
        static void Main(string[] args)
        {
            List<Container> table1 = new List<Container>()
            {
                new Container { Column1 = "Sam", Column2 = "Fred" },
                new Container { Column1 = "Arnold", Column2 = "Frank" }
            };

            List<Container> table2 = new List<Container>()
            {
                new Container { Column1 = "Whitwicky", Column2 = "Flintstone" },
                new Container { Column1 = "Schwartz", Column2 = "Sinatra" }
            };

            var result = Example.MergeTables(table1, table2);

            foreach (var r in result)
            {
                Console.WriteLine(r.Column1 + "\t\t" + r.Column2);
            }

            Console.ReadLine();
        }
    }

    public class Example
    {
        public static IEnumerable<Container> MergeTables(List<Container> table1, List<Container> table2)
        {
            return table1.Select((value, index) =>
                new Container
                {
                    Column1 = value.Column1 + " " + table2[index].Column1,
                    Column2 = value.Column2 + " " + table2[index].Column2
                });

        }
    }

    public class Container
    {
        public string Column1 { get; set; }
        public string Column2 { get; set; }
    }
}