Home > Enterprise >  C# Refactor LINQ query of Dictionary into a single lambda expression [closed]
C# Refactor LINQ query of Dictionary into a single lambda expression [closed]

Time:09-17

I am relatively new C# programmer and trying to improve my LINQ query skills. I prefer using method chaining for my queries but I am struggling. Is it possible to refactor this LINQ into a single lambda expression? The code here is a simplified example. My goal is to return the Value of Key=1 in a single line. I want the LINQ query to search and return a string value of Key 1 in single Lambda expression. Thanks!

using System;
using System.Collections.Generic;
using System.Linq;

namespace DictionaryPractice
{
    class Program
    {        
        static void Main(string[] args)
        {
            Dictionary<int, string> myd = new Dictionary<int, string>();
            myd.Add(1, "one");
            myd.Add(2, "two");
            myd.Add(3, "three");
            myd.Add(4, "four");
            
            foreach (var i in myd)
                Console.WriteLine(i.Value);
            Console.WriteLine("");

            var b = myd.Where(c => c.Key == 1).Select(c => c.Value).ToList();
            Console.WriteLine($"Desired output: {b[0]}");
        }
    }
}

CodePudding user response:

Is it possible to refactor this LINQ into a single lambda expression?

Ignoring the inefficiency of querying a dictionary for a single key value with Linq, no, there is no way to do a non-trivial Where and a non-trivial Select in a single lambda.

At best you could create a "filtered select" extension method where you pass in two lambdas, but I don't see the value of that over calling two Linq functions.

If you want to get rid of the ToList and the indexer, you could use something like Single instead of ToList to return a single value. Read the docs on Single, SingleOrDefault, First, and FirstOrDefault to understand the differences and determine which is appropriate for your needs.

CodePudding user response:

Dictionary can have only an unique key. So it doesn't make any sense to use linq and tolist() if you looking searching keys. Try this

 Console.WriteLine($"Desired output: {myd[1] }");

output

Desired output: one

it makes sense only if you have more complicated search like this

var list =  myd.Where(v => v.Key > 2).Select(v =>v.Value).ToList();

but it is one line only. What do you need? A half of line?

or maybe this?

Console.WriteLine( myd.Where(v => v.Key ==1).Select(v =>v.Value).FirstOrDefault());

but it is the same as the first one, only not so efficient

  • Related