2012-01-06 17 views
0

我有2個excel文件,我已經轉換成列表。第一個文件有我需要的所有項目的完整列表。但是,第二個列表中有一小部分需要在第一個列表中更改的項目。 這是我的第一個名單是如何構建的:構建如何將2個LINQ詞典合併爲1?

IEnumerable<ExcelRow> queryListA = from d in datapullList 
              select new ExcelRow 
              { 
               Company = d.GetString(0), 
               Location = d.GetString(1), 
               ItemPrice = d.GetString(4), 
               SQL_Ticker = d.GetString(15) 
              }; 

第二屆名單中非常相似的方式:

IEnumerable<ExcelRow> queryListB = from dupes in dupespullList 
              select new ExcelRow 
              { 
               Company = d.GetString(0), 
               Location = d.GetString(1), 
               NewCompany = d.GetString(4) 
              }; 

所以,如果有一家公司從1日列表中的特定位置匹配第二個清單,那麼公司將被更改爲新的公司名稱。

然後,我的最終列表應該包含第一列表中的所有內容,但是第二列表中指定的更改應該包含在內。

我一直在爲此奮鬥了幾天。讓我知道你是否需要更多細節。

[更新:]我很新LINQ和C#。我在網上找到了關於Office 2003的Excel閱讀器的代碼。如何從以下所有類創建1列表(如上所述)? 我ExcelRow類:

class ExcelRow 
{  
    List<object> columns; 

    public ExcelRow() 
    { 
     columns = new List<object>(); 
    } 

    internal void AddColumn(object value) 
    { 
     columns.Add(value); 
    } 

    public object this[int index] 
    { 
     get { return columns[index]; } 
    } 

    public string GetString(int index) 
    { 
     if (columns[index] is DBNull) 
     { 
      return null; 
     } 
     return columns[index].ToString(); 
    } 

    public int Count 
    { 
     get { return this.columns.Count; } 
    } 
} 

我ExcelProvider類:

class ExcelProvider : IEnumerable<ExcelRow> 
{ 
    private string sheetName; 
    private string filePath; 
    private string columnName1; 
    private string columnName2; 
    private List<ExcelRow> rows; 

    public ExcelProvider() 
    { 
     rows = new List<ExcelRow>(); 
    } 

    public static ExcelProvider Create(string filePath, string sheetName, string columnName1, string columnName2) 
    { 
     ExcelProvider provider = new ExcelProvider(); 
     provider.sheetName = sheetName; 
     provider.filePath = filePath; 
     provider.columnName1 = columnName1; 
     provider.columnName2 = columnName2; 
     return provider; 
    } 

    private void Load() 
    {    
     string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties= ""Excel 8.0;HDR=YES;IMEX=1""";    
     connectionString = string.Format(connectionString, filePath); 
     rows.Clear(); 
     using (OleDbConnection conn = new OleDbConnection(connectionString)) 
     { 
      try 
      { 
       conn.Open(); 
       using (OleDbCommand cmd = conn.CreateCommand()) 
       { 
        cmd.CommandText = string.Format("SELECT * FROM [{0}$] WHERE {1} IS NOT NULL AND {2} <> \"{3}\"", sheetName, columnName1, columnName2, null); 
        using (OleDbDataReader reader = cmd.ExecuteReader()) 
        { 
         while (reader.Read()) 
         { 
          ExcelRow newRow = new ExcelRow(); 
          for (int count = 0; count < reader.FieldCount; count++) 
          { 
           newRow.AddColumn(reader[count]); 
          } 
          rows.Add(newRow); 
         } 
        } 
       } 
      } 
      catch (Exception ex) 
      { throw ex; } 
      finally 
      { 
       if (conn.State == System.Data.ConnectionState.Open) 
        conn.Close(); 
      } 
     } 
    } 

    public IEnumerator<ExcelRow> GetEnumerator() 
    { 
     Load(); 
     return rows.GetEnumerator(); 
    } 

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() 
    { 
     Load(); 
     return rows.GetEnumerator(); 
    } 
} 

所以,使用所有這樣的邏輯,我怎麼能解決我的問題?

回答

1
//first create a dictionary of comapny whose name has been changed 
    var dict = queryListB.ToDictionary(x => x.Company, y => y.NewCompany); 

    //loop on the first list and do the changes in the first list 
    queryListA.ForEach(x => 
         { 
          if(dict.Keys.Contains(x.Company)) 
           x.Company = dict[x.Company]; 
         }); 
+0

我覺得OP是要求在位置匹配,以及:「所以,如果有一個公司從一個特定的位置** **在符合第二個1日列表列表,然後公司變更爲新公司名稱「 – Joey 2012-01-06 09:52:41

+0

是的,這正是我所需要的。感謝@Joey的澄清。 – 2012-01-06 14:11:55

0

我敢肯定,你可以寫簡單的代碼來達到同樣的目標,但我已經爲減少您必須通過第一和第二列表迭代次數的方式。如果性能不是問題,則只需在duapupList中搜索datapullList中的每個元素即可。

var excelRowCreator = new ExcelRowCreator(dupespullList); 
var finalRows = excelRowCreator.CreateExcelRows(datapullList); 

// ... 

public class ExcelRowCreator 
{ 
    /// <summary> 
    /// First key is company name, second is location 
    /// and final value is the replacement name. 
    /// </summary> 
    private readonly IDictionary<string, IDictionary<string, string>> nameReplacements; 

    /// <summary> 
    /// I don't know what type of objects your initial 
    /// lists contain so replace T with the correct type. 
    /// </summary> 
    public ExcelRowCreator(IEnumerable<T> replacementRows) 
    { 
     nameReplacements = CreateReplacementDictionary(replacementRows); 
    } 

    /// <summary> 
    /// Creates ExcelRows by replacing company name where appropriate. 
    /// </summary> 
    public IEnumerable<ExcelRow> CreateExcelRows(IEnumerable<T> inputRows) 
    { 
     // ToList is here so that if you iterate over the collection 
     // multiple times it doesn't create new excel rows each time 
     return inputRows.Select(CreateExcelRow).ToList(); 
    } 

    /// <summary> 
    /// Creates an excel row from the input data replacing 
    /// the company name if required. 
    /// </summary> 
    private ExcelRow CreateExcelRow(T data) 
    { 
     var name = data.GetString(0); 
     var location = data.GetString(1); 

     IDictionary<string, string> replacementDictionary; 
     if (nameReplacements.TryGetValue(name, out replacementDictionary)) 
     { 
      string replacementName; 
      if (replacementDictionary.TryGetValue(location, out replacementName)) 
      { 
       name = replacementName; 
      } 
     } 

     return new ExcelRow 
     { 
      Company = name, 
      Location = location, 
      ItemPrice = data.GetString(4), 
      SQL_Ticker = data.GetString(15) 
     }; 
    } 

    /// <summary> 
    /// A helper method to create the replacement dictionary. 
    /// </summary> 
    private static IDictionary<string, IDictionary<string, string>> CreateReplacementDictionary(IEnumerable<T> replacementRows) 
    { 
     var replacementDictionary = new Dictionary<string, IDictionary<string, string>>(); 
     foreach (var dupe in replacementRows) 
     { 
      var name = dupe.GetString(0); 
      IDictionary<string, string> locationReplacements; 
      if (!replacementDictionary.TryGetValue(name, out locationReplacements)) 
      { 
       locationReplacements = new Dictionary<string, string>(); 
       replacementDictionary[name] = locationReplacements; 
      } 

      locationReplacements[dupe.GetString(1)] = dupe.GetString(4); 
     } 

     return replacementDictionary; 
    } 
} 

UPDATE:包裝爲一類,並寫在Visual Studio所以不應該有任何語法錯誤。

+0

忽略我的答案片刻,剛注意到公司要求更改名稱的位置和名稱相同。更新我的解決方案,以便檢查它。 – Joey 2012-01-06 09:06:55

+0

答覆已更新。 – Joey 2012-01-06 09:55:20

1

循環遍歷queryListA並查看queryListB中是否有匹配的公司。如果是,則更新Company屬性。

下面的代碼:

foreach (var companyA in queryListA) 
{ 
    var companyBMatch = queryListB.FirstOrDefault(x => x.Company == companyA.Company && x.Location == companyA.Location); 
    if (companyBMatch != null) 
    companyA.Company = companyBMatch.NewCompany; 
} 
+0

這是否仍然保留我列表中的所有其他項目,還是需要再次構建它們? – 2012-01-09 21:46:02

+0

是的,它仍然保持其他項目。 – Paul 2012-01-10 02:44:54

+0

這是一個新手問題。我怎樣才能從這個循環中創建一個列表? – 2012-01-15 21:48:33