簡體   English   中英

將列表轉換為字典C#

[英]Convert A List To Dictionary C#

我已經使用Linq實現了一個搜索選項,它的工作原理如下:

string[] str = txtSearch.Text.Replace(" ", "").Split(',');

var con = (from c in context.Customer
           join d in context.CustomerType on c.CustType equals d.ID
           where str.Any(t => c.CustName.Contains(t))
           select new { c.CustomerID, c.CustName, c.CustAddress, d.Type }).ToList();

grdDetails.DataSource = con;
grdDetails.DataBind();

但是我聽說過Dictionary可以很好地進行查找,而不是List 因此,我嘗試執行以下操作,但未顯示任何數據:

編輯:我已經為Dictionary編輯了以下內容,但是好像我使用EF一樣 ,我必須遍歷List才能使用Dictionary 順便說一句,兩個字典中的鍵之間沒有關系。 因此,我想,雖然嘗試了另一種方法,但不會進行查找。 它可以工作,但是想知道這是否是一個好習慣。

var dictionary = new Dictionary<int, Customer>();
dictionary.Add(1, new Customer() { CustomerID = 1, CustName = "AT", CustType = 1 });
dictionary.Add(2, new Customer() { CustomerID = 2, CustName = "AT-2017", CustType = 1 });
dictionary.Add(3, new Customer() { CustomerID = 3, CustName = "Jackson", CustType = 1 });
dictionary.Add(4, new Customer() { CustomerID = 4, CustName = "Anderson", CustType = 1 });

var dictionary2 = new Dictionary<int, CustomerType>();
dictionary2.Add(1, new CustomerType() { ID = 1, Type = "Active" });

//dictionary.Keys.Where(key => key.Contains("AT")).ToList();

var con = (from c in dictionary
           join d in dictionary2 on c.Value.CustType equals d.Value.ID 
           where str.Any(t => c.Value.CustName.Contains(t))
           select new { c.Value.CustomerID, c.Value.CustName, d.Value.Type }).ToList();

grdDetails.DataSource = con;
grdDetails.DataBind();

我試圖遵循的教程最后將Dictionary轉換為List 但是我不確定為什么這樣做。 所以我想知道以上方法是否是使用Dictionary進行搜索的理想方法。

注意:我已經在控制台應用程序中使用過Dictionary ,並且我理解了它是如何工作的。 但是對於使用Dictionary進行加入卻有些困惑。

您的查詢輸出仍然是一個列表,因此con.Values會被編譯感到驚訝。

另外,第二個代碼示例對兩個初始化但未填充的字典運行查詢,因此沒有數據是正確的結果。

我懷疑您的第一個代碼示例如果針對數據庫,則更好。 它將使用數據庫的優化來運行查詢並返回結果。 將所有內容首先加載到內存然后運行查詢確實沒有任何優勢。

暫無
暫無

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

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