Convert a switch to linq

2

Is there any way to convert this SWITCH to LINQ ?

switch (row["grupo"])
{
    case "Genera ICAs":
        enuMetodo = TipoMovimientosStock.GeneraIca;
        break;
    case "Genera Remito de Compras":
        enuMetodo = TipoMovimientosStock.GeneraRemitoCompra;
        break;
    case "Genera ECAs":
        enuMetodo = TipoMovimientosStock.GeneraEca;
        break;
    case "Enciende Usa Partida":
        enuMetodo = TipoMovimientosStock.EnciendeUsaPartida;
        break;
}
    
asked by Nahuel Picca 12.09.2017 в 17:26
source

1 answer

3

Although you have not clarified if TipoMovimientosStock is a enum , as everything points to if I'm going to risk adding an answer, since I find it interesting to show the method that I will explain below.

There is a possibility to do what you want using the Description attribute that can be applied to enum . The first thing you should add:

using System.ComponentModel;

to be able to use the mentioned attribute Description .

Subsequently, modify your enum in the following way:

public enum TipoMovimientosStock
{
    [Description("Genera ICAs")]
    GeneraIca,
    [Description("Genera Remito de Compras")]
    GeneraRemitoCompra,
    [Description("Genera ECAs")]
    GeneraEca,
    [Description("Enciende Usa Partida")]
    EnciendeUsaPartida
}

Once this is done, we can use LINQ to compare the value you have in row["grupo"] with the description we have added to the enumeration:

enuMetodo = Enum.GetValues(typeof(TipoMovimientosStock)).Cast<TipoMovimientosStock>()
       .FirstOrDefault
       (value =>
   (Attribute.GetCustomAttribute(value.GetType().GetField(value.ToString()), typeof(DescriptionAttribute)) as DescriptionAttribute)
      .Description == row["grupo"]);

You must bear in mind that for this method to work, all the options of your enumeration must have a [Description("")] attribute (even if it is empty) since otherwise the code will fail with a NullReferenceException .

Anyway given the small number of options, performance and possibly code clarity, I would keep the switch . This method could be worth it if the number of options in your enum was higher.

    
answered by 12.09.2017 / 18:20
source