Linq Select
and FirstOrDefault(Func)
both have internal iterators, as well as JsonConvert.SerializeObject
. So, if you count them, then you have at least 4 iterators going inside your method. You can at reduce that by combining Select
and FirstOrDefault(Func)
with a single iterator something like :
private IEnumerable<dynamic> GetData(IEnumerable<dynamic> listD)
{
List<dynamic> data = new List<dynamic>();
foreach (var item in listD)
{
if(item == null) continue;
var responseList = new List<RepHelper>();
string repTitle;
if(item?.Pro != null)
{
foreach(var pro in item.Pro)
{
if(pro == null) continue;
var rep = new RepHelper { Res = pro.Rep, Title = pro.Title };
if(repTitle == null && rep.Res == true)
{
repTitle = rep.Title;
}
responseList.Add(rep);
}
}
data.Add(new
{
Id = item.Id,
Auteur = item?.AspNetUsers?.Init ?? string.Empty,
NiveauCode = item?.Niveau?.Code ?? string.Empty,
NiveauTextColeur = item?.Niveau?.TextColeur ?? string.Empty,
Rep = repTitle ?? string.Empty,
IdParent = item?.Id_Parent ?? -1,
allReponse = responseList.Count > 0 ? JsonConvert.SerializeObject(responseList) : string.Empty,
});
}
return data;
}
Now, since you're returning IEnumerable
, why not use yield return
instead of initializing a List<dynamic>
? so your work would be like :
private IEnumerable<dynamic> GetData(IEnumerable<dynamic> listD)
{
foreach (var item in listD)
{
// same code here ....
yield return new
{
Id = item.Id,
Auteur = item?.AspNetUsers?.Init ?? string.Empty,
NiveauCode = item?.Niveau?.Code ?? string.Empty,
NiveauTextColeur = item?.Niveau?.TextColeur ?? string.Empty,
Rep = repTitle ?? string.Empty,
IdParent = item?.Id_Parent ?? -1,
allReponse = responseList.Count > 0 ? JsonConvert.SerializeObject(responseList) : string.Empty,
};
}
}
You can also go IEnumerable
all the way, with something like this :
private string _repTitle;
private bool _hasRepHelperCollection;
private IEnumerable<dynamic> GetData(IEnumerable<dynamic> source)
{
foreach (var item in source)
{
if(item != null)
{
_hasRepHelperCollection = false;
_repTitle = null;
var allPro = GetRepHelper(item?.Pro);
yield return new
{
Id = item.Id,
Auteur = item?.AspNetUsers?.Init ?? string.Empty,
NiveauCode = item?.Niveau?.Code ?? string.Empty,
NiveauTextColeur = item?.Niveau?.TextColeur ?? string.Empty,
Rep = _repTitle ?? string.Empty,
IdParent = item?.Id_Parent ?? -1,
allReponse = _hasRepHelperCollection ? JsonConvert.SerializeObject(allPro) : string.Empty
};
}
}
}
private IEnumerable<RepHelper> GetRepHelper(IEnumerable<dynamic> source)
{
if(source == null)
yield break;
foreach(var item in source)
{
if(item != null)
{
var rep = new RepHelper { Res = response.Rep, Title = response.Title };
if(_repTitle == null && rep.Rep)
{
_repTitle = rep.Title;
}
if(!hasRepHelperCollection)
_hasRepHelperCollection = true;
yield return rep;
}
}
}
dynamic
in performance-sensitive code. \$\endgroup\$