none
how add ternary operator or if else condition in where condition with list using linq or lambda expression in c# RRS feed

  • Question

  • I have a generic list named lstofitems which has the below parameter

    id="123" -> string type
    type="LNG" -> string type
    mnvalue='' -> char type
    user="ABC" -> string type

    lstofitems.Where(systype => (systype.type.Contains("LNG") || systype.type.Contains("SMT") || systype.type.Contains("HBA")))
    .Select(systype => { systype.mnvalue = 'N'; return systype; })
    .ToList();
    lstofitems.Where(systype => systype.type.Contains("SHT"))
    .Select(systype => { systype.mnvalue = 'S'; return systype; })
    .ToList();

    Instead of checking "LNG" and "SHT" separately and then assigning to the list, Is there any way I can use "if else" or ternary operator and assign in single line(I mean update the mnvalue in the list within single statement)? Thanks in advance.

    Wednesday, April 10, 2019 3:04 PM

Answers

  • Fixed the above issue using if else in select (lamda expression) , as below. Now the list is updated with correct value:-

    lstofitems.Select(y =>
                {
                    if (y.type.Contains("LNG") || y.type.Contains("SMT") || y.type.Contains("HBA"))
                    {
                        y.mnvalue = 'N';
                        return y;
                    }
                    else
                    {
                        y.mnvalue = 'S';
                        return y;
                    }
                }).ToList();

    Wednesday, April 10, 2019 6:50 PM