Intersection lists

Is there a better, more elegant and concise way to get the intersection of two lists in C #?

In C #, a method for calculating the intersection of a list of dates:

public List<DateTime> dates_common(Timeserie ts1, Timeserie ts2) { var dt1 = new HashSet<DateTime>(ts1.dates); var dt2 = new HashSet<DateTime>(ts2.dates); dt1.IntersectWith(dt2); var dt = new DateTime[dt1.Count]; dt1.CopyTo(dt); return new List<DateTime>(dt); } 

In Ruby, this can be done like this:

 def dates_common(ts1, ts2) dt1 = ts1.dates.to_set dt2 = ts2.dates.to_set return dt1.intersection(dt2).to_a end 

The main reason for this awkwardness is the asymmetry between IEnumerable and specific containers and arrays.

I am constantly amazed at how poorly designed the standard C # libraries are, because such problems occur all the time.

Is there any better that means a more elegant and concise way to do this?

+4
source share
2 answers

You can use Enumerable.Intersect and Enumerable.ToList extension methods to get very elegant and concise code:

 public List<DateTime> dates_common(Timeserie ts1, Timeserie ts2) { return ts1.dates.Intersect(ts2.dates).ToList(); } 
+16
source
  // This function is used to remove those alias from 'cc' which are common in 'to' and 'cc' list. private static void RemoveCommonFromCc(ref List<string> to, ref List<string> cc) { IEnumerable<string> common = (List<string>)to.Intersect(cc); foreach(var removeCc in common) { cc.Remove(removeCc); } } 
0
source

Source: https://habr.com/ru/post/1381923/


All Articles