Best linq questions in May 2012

How to simultaneously sort 2 lists using LINQ?

17 votes

I have two lists { 7 3 5 } and {9 8 1}.

I want to sort my first list and I want the second list to have the same index permutation as given by the first list.

{3 5 7} => {8 1 9}

Is it possible to do this in a single LINQ statement?

Sounds like you might want:

var list1 = new List<int> { 7, 3, 5 };
var list2 = new List<int> { 9, 8, 1 };

var orderedZip = list1.Zip(list2, (x, y) => new { x, y } )
                      .OrderBy(pair => pair.x)
                      .ToList();
list1 = orderedZip.Select(pair => pair.x).ToList();
list2 = orderedZip.Select(pair => pair.y).ToList();

SQL reverse LIKE

7 votes

I have a table holding a list of countries. Say one of these countries is 'Macedonia'

What SQL query would return the 'Macedonia' record if a search is made for 'Republic of Macedonia'?

I believe that in linq it would be something like

var countryToSearch = "Republic of Macedonia";

var result =  from c in Countries
              where countryToSearch.Contains(c.cName) 
              select c;

Now what would the SQL equivalent for the query above be?

Had it been the other way round (i.e. the database has the long version of the country name stored) the below query should work:

Select * from country
where country.Name LIKE (*Macedonia*)

but I do not see how I can reverse it.

Side note: the country names in the table will always be the short version of country names

You can use CHARINDEX for this.

Select * from country
where CHARINDEX(country.Name, 'Republic of Macedonia') > 0

Is it faster to query a List<T> or database?

5 votes

I have recently had several situations where I need different data from the same table. One example is where I would loop through each "delivery driver" and generate a printable PDF file for each customer they are to deliver to.

In this situation, I pulled all customers and stored them into

List<Customer> AllCustomersList = customers.GetAllCustomers();

As I looped through the delivery drivers, I'd do something like this:

List<Customer> DeliveryCustomers = AllCustomersList.Where(a => a.DeliveryDriverID == DriverID);

My question: Is the way I'm doing it by querying the List object faster than querying the database each time for customer records associated with the delivery driver?

There isn't an accurate number for amount of rows that if you pass it you should query the DB instead in in-memory List<T>

But the rule of thumb is, DB are designed to work with large amount of data and they have optimization "mechanisms" while in in-memory there aren't such things.

So you will need to benchmark it to see if the round-trip to DB is worth it for that amount of rows for each time it's important to you

"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil"