How to convert this lambda expression to linq
As my title above how to convert this lambda into linq?
Have you every worked in Linq
to know how does it looks like ?
If the above specified code is not Linq
, then what is Linq
, Lambda
is an integral part of fluent
representation of the Linq
, since most of the APIs would need a Func delegate
, that's where Lambda
comes in.
Now regarding
x , q , z , b
, what do they represent ?
The Linq APIs are nothing but extension methods for IEnumerable<T>
, like List<T>
, Dictionary<TK,TV>
, whether we write the fluent' or the
Sqlsyntax these variables represent, each and every element in the collection, which is processed as part of logic provided by the
Func Delegate, you can certainly use and should use more credible variable to represent the exact thing, similar to other parts of code where
int x, float y, DateTime z` is a bad way to code
Regarding the statement posted above consider following changes:
- Rename
a,b
ascert,ts
, which refers to aCertificate
andTraining Schedule
classes respectively - Instead of generating anonymous type
new { a, b }
, create aclass
likeCerificateTrainingSchedule
that has all the elements of theCertificate
andTraining Schedule
class respectively, it would be easier to work as you move forward - Rename
x
ascts
, to represent combinedCerificateTrainingSchedule
If its easy to read then separate
Where
clause in multiple chains, like:.Where(cts => cts.a.Year.Value.Year == year)
.Where(cts => cts.a.TrainingTypeId.Value == trainingTypeId)
.Where(cts => cts.a.IsApproved.Value)
.Where(cts => cts.b.EndDate >= DateTime.Now)- Similarly the names of other variables can be modified to represent the true class and its objects, instead of random
a,b,c,d
. Also calls can be chained for clear understanding of the logic
Edit - // Modified Linq Query
// Joined / Merged version of Certificate and Training Schedule, add more fields as required, current one is based on certain assumptions of the fields / properties in the Certificate & TrainingSchedule classes respectively
public class CertificateTrainingSchedule
{
public int Year {get; set;} // Certificate Class Property
public int TrainingTypeId {get; set;} // Certificate Class Property
public bool IsApproved {get; set;} // Certificate Class Property
public DateTime EndDate {get; set;} // TrainingSchedule Class Property
}
var train = db.Certificates
.Join(db.TrainingSchedules, cert => cert.CertificateId, ts => ts.CertificateId, (cert, ts) => new CertificateTrainingSchedule{ Year = cert.Year, TrainingTypeId = cert.TrainingTypeId, IsApproved = cert.IsApproved,EndDate = ts.EndDate})
.Where(cts => cts.Year == year)
.Where(cts => cts.TrainingTypeId == trainingTypeId)
.Where(cts => cts.IsApproved)
.Where(cts => cts.EndDate >= DateTime.Now)
.Select(cts => new {cts.Year,cts.TrainingTypeId,cts.IsApproved})
.Distinct() // Allowing anonymous type to avoid IEqualityComparer<Certificate>
.Where(certMain => !db.Registrations.Where(s => s.EmployeeId == empId)
.Select(cert => new Certificate{Year = cert.Year,TrainingTypeId = cert.TrainingTypeId,IsApproved = cert.IsApproved})
.Any(cert => cert.CertificateId == certMain.CertificateId))
Convert Linq Query Expression into Linq Lambda Expression
You can use below code sample.
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp1
{
class University
{
public int Id { get; set; }
public string Name { get; set; }
}
class Student
{
public int Id { get; set; }
public int UniversityId { get; set; }
}
class Program
{
static void Main(string[] args)
{
IList<University> universities = new List<University>
{
new University { Id = 1, Name = "u1" },
new University { Id = 2, Name = "u2" }
};
IList<Student> students = new List<Student>
{
new Student { Id = 1, UniversityId = 1 },
new Student { Id = 2, UniversityId = 1 },
new Student { Id = 3, UniversityId = 2 },
new Student { Id = 4, UniversityId = 2 }
};
IEnumerable<Student> stus = universities
.Join(students, university => university.Id, student => student.UniversityId, (university, student) => new { university, student })
.Where(j => j.university.Name == "u2")
.Select(j => j.student);
}
}
}
How can I convert string to linq lambda expression in C#
It is possible to create string predicate with Dynamic Linq. Unfortunately, I am not familiar with it enough to tell how to iterate over a nested dictionary, so I use combined approach of a simple predicate $"Key == @0 && Value == @1"
and foreach
loop. You might want to learn more about this nuget package to get rid of foreach
loop.
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
namespace DynamicLinqDemo
{
internal class Program
{
static void Main(string[] args)
{
var item = GetDictionaryItem();
}
public static Dictionary<string, string> GetDictionaryItem()
{
var dict = new List<Dictionary<string, string>>()
{
new Dictionary<string, string>()
{
{"a","1-1" },
{"b","1-2" }
},
new Dictionary<string, string>()
{
{"a","1-3" },
{"b","1-4" }
}
};
var Field = "a";
var Context = "1-1";
string predicate = $"Key == @0 && Value == @1";
foreach (var item in dict)
{
var result = item.AsQueryable().Where(predicate, Field, Context).ToList();
if (result.Count > 0)
return item;
}
return null;
}
}
}
How to convert LINQ query to Lambda automatically
i found out how to do it. here is the screen shot.
Writing the Query expression directly without .ToList(), .FirstOrDefault(), SingleOrDefault()
will show the coresponding Lambda Expression in Lambda ExpressionTab.
How to convert LambdaExpression to ExpressionFuncT,bool in C#
The ExpressionHelper.GetLambda<T, bool>
method used to obtain the lambda expression hides its actual type, which is the desired Expression<Func<T, bool>>
, so all you need is to use a cast operator:
return (Expression<Func<T, bool>>)lambdaExpression;
Or better, either change the result type of ExpressionHelper.GetLambda<TSource, TDest>
to Expression<Func<TSource, TDest>>
, or don't use that helper method - when you know the generic type arguments at compile time, simply use one if the generic Expression.Lambda methods (ExpressionHelper.GetLambda<TSource, TDest>
seems to be the equivalent of Expression.Lambda<Func<TSource, TDest>>
), e.g.
var lambdaExpression = Expression.Lambda<Func<T, bool>>(parameterExpression, finalExpression);
How to convert this SQL query to LINQ or Lambda expression in C#?
You need to use somthing like this:
var result = Inventory
.GroupBy(x => x.ProductId)
.Where(x => x.Count() > 1)
.SelectMany(x => x.ToList())
.Select(x => x.Id);
Related Topics
Does Foreach Automatically Call Dispose
How to Get Modified Date from File in C# on Windows Mobile
Why Is Modulus Operator Not Working for Double in C#
Xmlserialize a Custom Collection with an Attribute
Get List<> Element Position in C# Using Linq
Text Property in a Usercontrol in C#
Comparing 2 Objects and Retrieve a List of Fields with Different Values
Detecting If Paste Event Occurred Inside a Rich Text Box
Maybe a C# Compiler Bug in Visual Studio 2015
A Way to Push Buffered Events in Even Intervals
Convert Datetime to a Specified Format
How to Get Full Host Name + Port Number in Application_Start of Global.Aspx
Entity Framework Db-First, Implement Inheritance
Moq + Unit Testing - System.Reflection.Targetparametercountexception: Parameter Count Mismatch