Filling Label with Linq using ToList ()?

2

I have a table with the following schemas:

GarantiaImovel | imovelID | GarantiasTipos
12             |    3     | Caução2
12             |    4     | Depósito
12             |    5     | Caução2
12             |    5     | Fiador
12             |    5     | Seguro Fiança

Then I have the following Query :

var garantias = (from p in db.T_GarantiasLocaticias
                         where p.imovelID == 5
                         select p.GarantiasTipos).ToList();

My intention in this Query is to return the three rows in the table above with the GaantiasTipo column, but I using foreach and it only returns me the last line as I can return in the following structure:

foreach (var garantia in garantias)
{
     lblGarantiaLocaticias.Text = garantia + ", ";
}

How to proceed?

    
asked by anonymous 16.08.2017 / 03:07

2 answers

1

If you do not need to do a foreach just use String.Join with the return of that expression # / p>

var garantias = (from p in db.T_GarantiasLocaticias
                  where p.imovelID == 5
                  select p.GarantiasTipos)
               .ToList();

lblGarantiaLocaticias.Text = String.Join(", ", garantias);

Online Example

You can even use a for or foreach or up to while , but there is no need anymore since https://msdn.microsoft.com/en-us/library/57a79xd0(v=vs.110).aspx">String.Join already does this in a transparent way > . Another observation is about what was happening, because it failed to accumulate the values already obtained in the interactions and that in the foreach of your question did not, in case it would just put a plus sign ( + ) before equal ( = ) ( which represents an addition assignment operator ) and a setting so that the last element does not have the comma (, ) this way :

lblGarantiaLocaticias.Text = "";
foreach (var garantia in garantias)
{
     if (lblGarantiaLocaticias.Text != "") 
         lblGarantiaLocaticias.Text += ", ";
     lblGarantiaLocaticias.Text += garantia;
}

References:

16.08.2017 / 03:53
1

You can use Aggregate(...) (in < > reduce ):

var garantias = (from p in db.T_GarantiasLocaticias
                 where p.imovelID == 5
                 select p.GarantiasTipos)
                .ToList()
                .Aggregate(string.Empty, (actual, novo) => 
                {
                    // caso a string concatenada nao esteja vazia,
                    // adiciona o separador
                    if(!string.IsNullOrEmpty(actual)) {
                        actual += ","
                    }

                    return actual + novo;
                });

You can see an example of Aggregate here .

    
16.08.2017 / 10:14