3
I have a C# method that receives a List<string>
and I must return a string with the list of members of the List<string>
ordered by number of occurrences and then alphabetically.
I did and it already worked, but not with the expected performance.
public string getMostOccuredString(IList<string> lista)
{
var mostOccured = lista
.GroupBy(a => a)
.Select(g => new { g.Key, Count = g.Count() })
.OrderByDescending(c => c.Count)
.ThenBy(c => c.Key);
string retorno = "";
foreach (var item in mostOccured)
{
retorno = retorno + ";" + item.Key;
}
return retorno;
}
Using "for" instead of "foreach" and Stringbuilder instead of concatenation can help improve performance.
– Samuel Renan Gonçalves Vaz
although it is a minimal difference in performance you could exchange this foreach for a string.Join that is relatively more elegant and slightly more performative, example:return = String.Join(";", mostOccured);
– Lucas Miranda
@Lucasmiranda the difference will be brutal, just does not do the same as this tie. It may even be that he wanted more the
Join()
that tie, but we have no way of knowing.– Maniero
ah yes, I didn’t see there that he was catching the key, well observed
– Lucas Miranda