Home > Back-end >  C# - LINQ - specific query select
C# - LINQ - specific query select

Time:08-14

I would like to get a specific select with the best performance possible

I currently have a code like this:

var getData = from x in dbContex.MyTable
                                            where x.Car == "audi"
                                            select x;

MyTable has three columns: Car ProductionYear Color

I would like to download a specific vehicle brand with the year of manufacture that has a specific color.

I am currently doing it with reference to the code above:

 foreach (var item in getData)
                {
                    if (item.color == "blue") item.ProductionYear = "1999";
                    if (item.color == "red") item.ProductionYear = "2003";

        // etc (...)
                }

I would like to assign a specific year for a given car and color if I find it.

A very prosaic example above.

Problem - I currently have 100 colors and only want to check 10 colors.

How can I do it faster so as not to search the entire list and not to use IF statements?

CodePudding user response:

Create an array of the colors, then use Contains method in the predicate expression:

var colors = new [] { "red", "blue" };

var results = dbContext.MyTable
    .Where( x => "audi" == x.Car
        && colors.Contains( x.color ) );

Then use a switch statement to assign your years:

foreach(var car in results)
{
    car.ProductionYear = car.color switch
    {
        "blue" => 1999,
        "red" => 2003,
        _ => // unexpected result, throw exception
    }
}

You could also define the years with the colors then work the year assignment into the LINQ query:

var colorYears = new []
{
    new {
        color = "red",
        ProductionYear = 2003,
    },
    ...
};

var colors = colorYears.Select( x => x.color ).ToArray();

var results = (...query from above...)
    // enumerate
    .ToArray()
    // join datasource results with your colorYears array
    // on the `color` property
    .Join( colorYears, 
        c => c.color, 
        cy => cy.color,
        ( c, cy ) => 
        {
            // assign the configured production year for the color
            c.ProductionYear = cy.ProductionYear;
            // return the entity
            return c;
        } );

CodePudding user response:

There is no scenario, where you don`t use if or switch clause. You want to change data, which is not LINQ case. Only thing I would do - go to switch, rather than If clause.

  • Related