Tuesday, May 9, 2017

a hack to doctor up reference type records midstream in a lambda expression in C#

Consider this code from this blog posting:

List<Om> thinYin = yinList.Result.Where(i => !yangList.Any(a => a.OmId ==
      i.OmId)).ToList();
List<Om> yinYang = yangList.Concat(thinYin).OrderBy(y => y.OmId).ToList();

 
 

Why don't we put it in a method like so:

public List<Om> Whatever(List<Om> yinList, List<Om> yangList)
{
   List<Om> thinYin = yinList.Result.Where(i => !yangList.Any(a => a.OmId ==
         i.OmId)).ToList();
   List<Om> yinYang = yangList.Concat(thinYin).OrderBy(y => y.OmId).ToList();
   return yinYang;
}

 
 

Alright, imagine a Venn (named for John Venn) diagram in which a yinList circle overlaps with a yangList circle. Well, above we are keeping all of the yangList and appending to it just the piece of the yinList that does not overlap with it. (That way there are no dupes in the list we ultimately craft.) There might be reasons why a yang would beat a yin. Perhaps its properties are better baked and farther along in a workflow if both the yang and yin come from different web services while being aggregated in a common report. And yet, let's say that a Zen getsetter on an Om object is always going to be considered more fresh on a yin than a yang due to a shortcoming of the yang web service. What should we do? Let's try this:

public List<Om> Whatever(List<Om> yinList, List<Om> yangList)
{   
   List<Om> throwAwayList = yangList.Where(a => yinList.Any(i => i.OmId == a.OmId
         && DoctorUp(i,a))).ToList();
   List<Om> thinYin = yinList.Result.Where(i => !yangList.Any(a => a.OmId ==
         i.OmId)).ToList();
   List<Om> yinYang = yangList.Concat(thinYin).OrderBy(y => y.OmId).ToList();
   return yinYang;
}
 
private bool DoctorUp(Om yin, Om yang)
{
   yang.Zen = yin.Zen;
   return true;
}

 
 

If Om is a reference type (a class not a struct) then it should be doctorupable inside a method without explicitly coming back from a method as a return type and then getting reassigned to the original variable. You can use the ref keyword if you like too. I guess you'd have to if Om were a struct, though I have not tried that firsthand to confirm it would work.

No comments:

Post a Comment