2017-01-23 34 views
0

我实现了使用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进行加入。

+1

在您的第一个代码块中,您为什么要将'CustType'加入到'ID'? '在c.CustType等于d.ID'这似乎没有道理。 –

+3

看来你正在处理EF或某种类型的Linq to SQL提供程序,在这种情况下,你的Linq代码只是被转换为SQL,并且容器的类型无关紧要。 – juharr

+0

感谢您的回复@juharr。是!我正在使用EF。那么你的意思是不需要使用'Dictionary'或不需要上述情况?我想知道是否可以用'Dictionary'来实现上面的内容。只是试图澄清。 –

回答

1

您的查询的输出仍然是一个列表,所以我很惊讶con.Values编译。

另外,第二个代码示例在两个已初始化但未填充的字典上运行查询,因此没有数据是正确的结果。

我怀疑你的第一个代码示例是更好的,如果它是针对数据库。它将使用数据库的优化来运行查询并返回结果。将所有内容加载到内存中然后运行查询确实没有任何优势。

+0

非常感谢@MikeS。我正在做数据库操作或关于数据库。我可以理解查询可以使用。但是很想知道我是否可以用'Dictionary'来制作它。顺便说一下,我使用EF。 –

+1

如果你想从你的查询中创建一个字典,就有一个ToDictionary方法,该方法接受表达式,这些表达式将形成关键字和每个条目的值。你会用这个替换你的ToList()。 – MikeS

+0

我编辑了我的答案@MikeS。 'Dictionary'工作并获取数据,但看看这是否有点接近我期待的方式。再次感谢您的评论。 –