Search code examples
c#linq

Using LINQ to populate a string with a single column value


Firstly, I have an Overrides SQL table (and a corresponding EF DB context), which has a Type, Value, and Override Value. The idea is that for a particular kind ("Type") of override, the code can check a particular value and go see if there is an override value that should be used instead.

var branchOverrides = overridesSqlContext.Overrides
  .Where(q => q.Type == "Branch Override")
  .Select(s => new
    {
      s.Value,
      s.OverrideValue
    });

In this case, I want the list of different override values of the "Branch Override" type. From there, I would like to be able to retrieve a specific override value at a given point within my code. How can I query the branchOverrides variable I've created to be able to say something like:

string readingOverride = select OverrideValue from branchOverrides where Value = "Reading"

My code will need to be able to read various override values for different branches at different points, and being able to query the branchOverrides variable at any point would seem like the ideal approach.

Thank you for any assistance on this.


Solution

  • You can use Single() on the query object you have:

    string readingOverride = branchOverrides
        .Single(bo => bo.Value == "Reading")
        .OverrideValue;
    

    This will throw an exception if an entry doesn't exist though so you probably want to use SingleOrDefault instead and check for a null return.

    Also note that the branchOverrides object here is an IQueryable<> which means that every time you use it, it will send a query to the database. You may want to materialise that to a local list by adding .ToList() after the Select(...). Alternatively, you may want to look at caching this data, especially if it's going to be used frequently.