Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I combine a foreach and a LINQ query into one?

Tags:

c#

linq

I have a C# code that looks like this:

foreach (var entry in this.ChangeTracker.Entries()
                     .Where(e => e.Entity is IAuditableTable &&
                                 e.State == EntityState.Added))
{
    IAuditableTable e = (IAuditableTable)entry.Entity;
    e.ModifiedDate = DateTime.Now;
}

This seems to be like a combination of foreach and LINQ. Can sometone tell me is it possible for me to remove the foreach and combine this into one LINQ statement

like image 391
Samantha J T Star Avatar asked May 09 '14 10:05

Samantha J T Star


People also ask

Is LINQ query faster than foreach?

LINQ syntax is typically less efficient than a foreach loop. It's good to be aware of any performance tradeoff that might occur when you use LINQ to improve the readability of your code.

Which loop is used to iterate in LINQ query?

The foreach loop is used to iterate over the elements of the collection. The collection may be an array or a list.

What collections can LINQ be used with?

You can use LINQ to query any enumerable collections such as List<T>, Array, or Dictionary<TKey,TValue>. The collection may be user-defined or may be returned by a . NET API.

How many ways can you write the LINQ query?

LINQ provides you three different ways to write a LINQ query in C# or VB.


1 Answers

I'd suggest not doing this. Keep everything as readable as possible:

var auditableTables = this.ChangeTracker.Entries()
                                        .Where(e => e.State == EntityState.Added)
                                        .Select(e => e.Entity)
                                        .OfType<IAuditableTable>();

foreach (var table in auditableTables)
{
    table.ModifiedDate = DateTime.Now;
}

My rule of thumb for coding - if you can't read it like a sentence, then it needs fixing.

like image 50
dav_i Avatar answered Sep 19 '22 18:09

dav_i