C# Union/Order by with LINQ and Performance

Asked

Viewed 280 times

4

Imagine the following situation there are 3 classes class A, class B, class C, class A has many classes B and many classes C. class B has many classes C. clsse C has a data datetime 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;
}

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

now imagine that the class A is instantiated sometimes, and use this search a lot, what would be a good solution taking into account the "performance" in this case?

1 answer

3

Query

There are two possibilities. In the title refers to Union (that is, without repeated elements if they exist), so 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 results (repeated included) (as indicated in the question, all classes of C in A and C classes of each class B) the query would be:

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

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

Already the second query, the Concat() only returns entries from both lists.

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

Use of the search

Regarding the use of the search multiple times depends on the frequency of updating the source data. Could you explain in more detail how class A will be changed? Whether to go to the database at each access or store the first read values in memory?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.