我实现了使用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'来实现上面的内容。只是试图澄清。 –