2016-09-04 43 views
-2

有2个不等长的列表,我想合并成单个列表。组合不等长度列表

var dataresource = (from det in dbobj.tbls1 
            where det.WorkTypeId == 1 
              select new 
              { 
               resnum = sowdet.number, 


              }).ToList(); 

var datafixed = (from det123 in dbobj.tbls1 
            where det123.WorkTypeId == 2 
              select new 
              { 
               fixednum = det123.number, 

              }).ToList(); 

dataresource包含的值(A,B,C)

datafixed包含的值(d,E,F,G,H)

结果预期是

Resultlist = 
A D 
B E 
C F 
null G 
null H 

尝试过使用.Zip()但无法处理不等大小的列表。

+0

快速谷歌搜索:http://stackoverflow.com/questions/19522233/how-to-combine-multiple-lists-of-same-or-different-lengths-in -linq,http://stackoverflow.com/questions/1190657/add-two-lists-of-different-length-in-c-sharp – null

+0

试过这个,但值重复,没有得到预期的结果。 – yeshu

+1

我认为没有linq会更容易,只需迭代列表并添加到第三个。无论如何,我没有得到你的“预期结果”,为什么有空值? – null

回答

-1

试试这个

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Data.SqlClient; 
using System.Data; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      List<string> datasource = new List<string>() { "A", "B", "C" }; 
      List<string> datafixed = new List<string>() { "D", "E", "F", "G", "H" }; 

      var results1 = datasource.Select((x,i) => new { source = x, fix = i < datafixed.Count ? datafixed[i] : null}).ToList(); 
      var results2 = datafixed.Select((x, i) => new { source = x, fix = i < datasource.Count ? datasource[i] : null }).ToList(); 

     } 
    } 
}