tags:

views:

1574

answers:

1

Here's the LINQ query I have, it gets the unique value for each selected column and stores them as a list in a dictionary.

        var serialTable = serialNoAdapter.GetData();
        var distinctValue = (from row in serialTable
                        select new
                                   {
                                       row.CodePractice,
                                       row.LockType,
                                       row.Software
                                  }).Distinct().ToList();
        var softwareValue = distinctValue.Select(p => p.Software).Distinct().ToList();
        var codeValue = distinctValue.Select(p => p.CodePractice).Distinct().ToList();
        var lockValue = distinctValue.Select(p => p.LockType).Distinct().ToList();

        return new Dictionary<string, List<string>>()
                   {
                       {"software", softwareValue},
                       {"codepractice", codeValue},
                       {"locktype", lockValue}
                   };

The only problem is it is broken up into a few statements. My question is is it possible to simplify it and compact it into a single statement?

+2  A: 

I believe you can simplify it substantially by ommitting the middle step.

        var softwareValue = serialTable.Select(p => p.Software).Distinct().ToList();
        var codeValue = serialTable.Select(p => p.CodePractice).Distinct().ToList();
        var lockValue = serialTable.Select(p => p.LockType).Distinct().ToList();

        return new Dictionary<string, List<string>>()
               {
                   {"software", softwareValue},
                   {"codepractice", codeValue},
                   {"locktype", lockValue}
               };

Maybe others can improve further.

Jay Bazuzi
With this approach, i think you are querying the database 3 times instead of 1...is it the case?
Ngu Soon Hui
Probably. Whether that matters, and how to optimize properly, will depend on your exact circumstances. Profile with real data.
Jay Bazuzi