我實現了使用LINQ如下工作正常搜索選項:轉換列表來解釋C#
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
進行加入。
在您的第一個代碼塊中,您爲什麼要將'CustType'加入到'ID'? '在c.CustType等於d.ID'這似乎沒有道理。 –
看來你正在處理EF或某種類型的Linq to SQL提供程序,在這種情況下,你的Linq代碼只是被轉換爲SQL,並且容器的類型無關緊要。 – juharr
感謝您的回覆@juharr。是!我正在使用EF。那麼你的意思是不需要使用'Dictionary'或不需要上述情況?我想知道是否可以用'Dictionary'來實現上面的內容。只是試圖澄清。 –