AT-2017
AT-2017

Reputation: 3149

Convert A List To Dictionary C#

I've implemented a search option using Linq that works fine as follows:

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();

But I heard about Dictionary that works very well for lookup rather than List. So I've tried to do the following but doesn't get any data to show:

Edited: I've edited the following for Dictionary but it seems like if I work with EF, I have to loop through the List to get with Dictionary. By the way, there are no relation between the keys in both dictionaries. So I guess, there would be no lookup though tried in another way. It works but want to know if it's a good practice.

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();

I was trying to follow a tutorial that converts a Dictionary into List at the end. But I am not sure about it why it has done so. So I would like to know if the above way is the perfect one to do the search using Dictionary.

Note: I've used Dictionary in the console application and I understood how it works. But little bit confused to do the joining using Dictionary.

Upvotes: 0

Views: 194

Answers (1)

MikeS
MikeS

Reputation: 1764

The output of your query is still a list so I'm surprised the con.Values compiles.

Also, the second code example is running a query on two initialized but not populated dictionaries, so no data is a correct result.

I suspect your first code example is better if it is going against the database. It will use the database's optimization to run the query and return the results. There really wouldn't be any advantage of loading all that into memory first then running a query.

Upvotes: 1

Related Questions