There are two variables whose value can be either empty or a value of the type "city"

var blago = sum5 + sum6>0?"Благовещенск":""; var moskva = sum7 + sum8 + sum9>0?"Москва":""; 

I want to combine both strings into one, but it may be that one of the variables is empty and then Благовещенск, can turn Благовещенск, , and Благовещенск should turn out without a comma.

 var rezCity = blago+","+moskva; 
  • You have a comma not standing there, you need a comma in the condition - nick_n_a
  • I don't know what input you have, so I’ll write this: var rezCity =blago + ( ((blago.ToString()=="") || (moskva.ToString()==""))?"":"," )+moskva; If the blago is a priori filled, the condition can be simplified. - nick_n_a
  • Or so var rezCity =blago + ( ((sum6>0) && (sum9>0))?",":"" )+moskva; - nick_n_a

2 answers 2

The easiest way to do this is through lists of strings:

 var cities = new List<string>(); if (sum5 + sum6 > 0) cities.Add("Благовещенск"); if (sum7 + sum8 + sum9) cities.Add("Москва"); var rezCity = string.Join(",", cities); 

If the variables blago and moskva mandatory for use, you need to check them. And to teach logic: obviously, a comma should be put when both variables are filled:

 var rezCity = blago + (blago != "" && moskva != "" ? "," : "") + moskva; 

    You can do the following. Leave the blago and moskva as it is:

     var blago = sum5 + sum6>0?"Благовещенск":""; var moskva = sum7 + sum8 + sum9>0?"Москва":""; 

    Write a helper function to combine the strings into one through a separator (except for empty ones), for example:

     string Join(string separator, params string[] s) { return String.Join(separator, s.Where(x => !String.IsNullOrEmpty(x))); } 

    Calling her will give the desired result:

     // Join(",", "Благовещенск", "Москва") вернет Благовещенск,Москва // Join(",", "", "Москва") вернет Москва // Join(",", "Благовещенск", "") вернет Благовещенск var resCity = Join(",", blago, moskva); 
    • Didn't your mom tell you that it is not good to pass functions with side effects to linq-methods? What is the usual foreach loop for you? The call to Aggregate is unreadable ... - Pavel Mayorov
    • And how is the stock string.Join different? - VladD
    • @VladD here a method with filtering of empty lines. Stock filters nothing. - Pavel Mayorov
    • @PavelMayorov: Ah, exactly. Then I would not make a bike, but filtered out empty lines (for example, using Where ). - VladD
    • well, instead of a new function, you could just create an array / list: new [] {blago, moskva} - Grundy