C # Union / Order by with LINQ and Performance

4

Imagine the following situation there are 3 classes Class A, class B, class C, class A has many B classes and many C classes. class B has many C classes. the clsse C has a datetime date field.

public class A
{
  DBContext db = new ClassesContext();
  public IEnumerable<B> classesB{get; set;}
  public IEnumerable<C> classesC{get; set;}

  public IEnumerable<C> retornaTodasC()
  {
    var classes = ....
    return classes;
  }
}

public class B
{
 public IEnumerable<C> classesC{get; set;}
}
public class C
{
 public datetime Data;
}

As would be a search (made by class A) to the database using LINQ, order by, of all classes C of class A and classes C of each class B within that same class A, sorted by date and storing all classes 3 in a "var classes"?

Now imagine that class A is instantiated mtas times, and use this search a lot, what would be a good solution considering the "performance" in this case?

    
asked by anonymous 07.05.2014 / 20:01

1 answer

3

Query

There are two possibilities. In the title refers to Union (that is, without repeated elements if they exist), therefore assuming the use of the operator the query would be:

var classes = ClassesB.SelectMany(b => b.classesC)
                      .Union(ClassesC)
                      .OrderBy(c => c.Data);

However, if you want to keep all the results (repeated in all cases) (as indicated in the question, all classes of C in A and of classes C of each class B) the query would look like:

var classes = ClassesB.SelectMany(b => b.classesC)
                      .Concat(ClassesC)
                      .OrderBy(c => c.Data);

In terms of performance impact, the first query has a greater impact since the .Union() operator will scroll through the first list, add the elements to an auxiliary list, and then cycle through the second list and return all objects that are not in the auxiliary list.

In the second query , Concat() only returns the elements of both lists.

In the end it will depend on whether you need the repeated elements in the final list.

Search Usage

Regarding the use of the search multiple times depends on the frequency of update of the source data. Could you explain in more detail how Class A will be changed? If it will go to the database at each access or will it save the values read the first time in memory?

    
08.05.2014 / 01:19