簡體   English   中英

C#-字典中有2個DataTable列-不同的值

[英]C# - 2 DataTable columns to Dictionary - Distinct Value

我有一個文本文件列表,正在閱讀每個文件,並在拆分選項的幫助下,創建了一個具有5列(無ID)的數據表(名稱:tbl)。

此外,創建僅具有Column1和Column5的數據表,並將其轉換為字典,因為column1將是鍵,而column5將是其值。

以下是代碼:

        string[] selectedColumns = new[] { "Column1", "Column5" };
        DataTable dt = new DataView(tbl).ToTable(false, selectedColumns);

        dict = dt.AsEnumerable().ToDictionary<DataRow, string, string>(row => row[0].ToString(),
                                   row => row[1].ToString());

錯誤: $ exception {“已經添加了具有相同鍵的項。”} System.Exception {System.ArgumentException}

該錯誤是由於重復而引起的。

    dict = dt.AsEnumerable().Distinct().ToDictionary<DataRow, string, string>(row => row[0].ToString(),
                               row => row[1].ToString());

結果成一樣。

dict = dt.AsEnumerable().ToDictionary<DataRow, string, string>(row => row[0].ToString(),
                                           row => row[1].ToString()).Distinct();

引發錯誤:錯誤1無法將類型'System.Collections.Generic.IEnumerable>'隱式轉換為'System.Collections.Generic.Dictionary'。 存在顯式轉換(您是否缺少演員表?)

如何避免重復並將僅不同的值放入字典dict中?

提前致謝。

作為錯誤狀態,您需要將其轉換為Dictionary

嘗試這個

            dict = dt.AsEnumerable().Select(row => new
            {
                attribute1_name = row.Field<string>(selectedColumns[0]),
                attribute2_name = row.Field<string>(selectedColumns[1])
            }).Distinct().ToDictionary(s => s.attribute1_name, s => s.attribute2_name);

也許您可以嘗試這樣的事情:

 dict = dt.AsEnumerable().GroupBy(x=> x.<yourColumnName>)
  .Select(group => group.First());

然后加載到字典中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM