What is the correct way to include multiple wheres in a LINQ call for OR
List<Pos> posList = DbContext.PosList
.Where<Pos>(p => p.Pos == "51000785" ||
p => p.Pos == "123")
.ToList<Pos>();
The Linq where clause takes one expression and returns one bool value. Yours is taking two expressions each with their own return value. You would need to combine these two into one lambda expression that returns one value rather than the two separate ones in your example.
List<Pos> posList = DbContext.PosList
.Where<Pos>(p => p.Pos == "51000785" || p.Pos == "123")
.ToList<Pos>();
Related
I want to use OR function in my linq query.
Ex:
Sql:
select * from tblusers where userid=1 and status='a' or status='b';
Linq:
var result= _Repository.selectAll().where(x=>x.UserID==1 && x.status=="a" OR x.status=="B");
It's does work for linq query. so does anyone have any idea?
So you are aware about the && operator for comparison, then why not make a try with || operator? Anyway here is the solution for your problem, Following code will get you the result with UserID is 1 and status is either a or B.
_Repository.selectAll().where(x=>x.UserID==1 && (x.status=="a" || x.status=="B"));
Create an array of status you want to check and then use contains. something like this.
var statusList = new[] {"a", "b"};
.Where(x=> x.UserID == 1 && statusList.Contains(x.status));
Adding my 2 cents in here, there is another way you can write your sql query in C# which more or less resembles the sql syntax.
var result = from x in _Repository.SelectAll() where x.UserID == 1 && (x.Status == "a" || x.Status == "B") select x;
This syntax is Query Syntax/Expression where as your snippet is Method Syntax/Expression. Both will achieve same results. Also behind the scene, query syntax is compiled to Method syntax.
At compile time, query expressions are converted to Standard Query Operator method calls according to the rules set forth in the C# specification. Any query that can be expressed by using query syntax can also be expressed by using method syntax. However, in most cases query syntax is more readable and concise.
Or other approach with List.Contains, which generates sql query like
SELECT * FROM tblusers WHERE userid=1 AND status IN ('a','b');
var acceptedStatus = new List<string> { 'a', 'b' };
var result= _Repository.selectAll()
.Where(x => x.UserID == 1)
.Where(x => acceptedStatus.Contains(x.Status));
Notice that instead of && operator you can use another Where function and chain them. Can be more readable then fit all conditions in one line.
Try code:
var result =( from x in _Repository.selectAll()
where x.UserID==1 && (x.status=="a" || x.status=="B") select x);
another Solution
var result =( from x in _Repository.selectAll().where(c=>c.status=="a" || x.status=="B")
where x.UserID==1 select x);
I am new to Lambda expression. I want a result from combination of two tables with where clause in lambda Expression , query runs fine but how to get result in variable after processing query??
var Rental = db.AUCDATA_COUPONS.Join(db.AUCDATA_TENORS,
c => c.AUCDT_ID,
o => o.AUCDT_ID,
(c, o) => new { c, o })
.Where(x => x.o.PRODUCT_ID == "SUKUK" && x.o.ISSUE_DATE == Convert.ToDateTime("02-MAR-12") && x.o.TENOR_ID == "03Y"
&& x.c.AUCDT_ID == x.o.AUCDT_ID && x.c.COUPON_NXTDT == Convert.ToDateTime("21-NOV-15"))
.Select(x => x.c.RENTAL_RATE);
db.AUCDATA_COUPONS is an IQueryable<T> (where T is the type of the class representing the table). The extension methods you use (like Join, Where and Select) take this IQueryable<T> and return a new IQueryable<T>.
The last Select returns an IQueryable<int> (or double depending of the type of RENTAL_RATE). The actual query (the lambdas) are only executed when you iterate through that IQueryable. You can do that with foreach
foreach(var rentalRate in Rental)
Maybe a better way is to convert the result to a list or array. This way you would execute the query only once and not again and again with every foreach you execute:
var list = Rental.ToList(); // results in an List<int>
// or
var array = Rental.ToArray(); // results in an int[]
Note that you'll probably need to change your datetime comparisons to
x.o.ISSUE_DATE.Date == new DateTime(2012,3,2)
and
x.c.COUPON_NXTDT.Date == new DateTime(2015,11,21)
for the query to work correctly.
You already have the results in the variable. But, depending on what you want to do with them, you can add .ToArray() or .ToList() after .Select(...).
I have the following expression that I am using in a linq to entities query
private Expression<Func<PageElement, bool>> ViewerProfileCheckExp(IViewerProfileModel vpSource)
{
return (pe) => pe.ViewerProfiles.Any(vp => vp.ViewLevel.Id == vpSource.ViewLevelId &&
vp.ViewTransitId == vpSource.ViewTransitId &&
vp.ViewGroups.ContainsAny(vpSource.Groups));
}
In the last clause I would like to be able to return true in the condition if any of the ViewGroups in vp are contained in vpSource.Groups. I realize that ContainsAny does not exist but I am wondering how to integrate what I want into the expression.
What you're logically looking for is whether or not the intersection of the two collections has any items:
vp.ViewGroups.Intersect(vpSource.Groups).Any()
I am trying to do something similar to my previous post, except I am using extension methods instead of LINQ. I get an error telling me that && cannot be used, so how would I search within a table using two strings entered by the user?
var query = (App.DBConnection.Table<Notes>().Where(
c => c.Note.Contains(textBox1.Text) && c => c.Note.Contains(textBox2.Text))).Single();
TextBox_Results.Text = query.Note;
Remove the second lambda operator c =>
var query = App.DBConnection.Table<Notes>()
.Where(c => c.Note.Contains(textBox1.Text)
&& c.Note.Contains(textBox2.Text)))
.Single();
Apart from that, i would use FirstOrDefault instead of Single. The latter throws an InvalidOperationException if there are no elements or if there are more than one. The former just returns null if no item matches the predicate in the Where.
You don't need to declare the c variable again
Where(c => c.Note.Contains(textBox1.Text) && c => c.Note.Contains(textBox2.Text)))
should be
Where(c => c.Note.Contains(textBox1.Text) && c.Note.Contains(textBox2.Text)))
How to set multiple values of a list object, i am doing following but fails.
objFreecusatomization
.AllCustomizationButtonList
.Where(p => p.CategoryID == btnObj.CategoryID && p.IsSelected == true && p.ID == btnObj.ID)
.ToList()
.ForEach(x => x.BtnColor = Color.Red.ToString(), );
In the end after comma i want to set another value.
What should be the expression, although i have only one record relevant.
Well personally I wouldn't write the code that way anyway - but you can just use a statement lambda:
A statement lambda resembles an expression lambda except that the statement(s) is enclosed in braces
The body of a statement lambda can consist of any number of statements; however, in practice there are typically no more than two or three.
So the ForEach call would look like this:
.ForEach(x => {
x.BtnColor = Color.Red.ToString();
x.OtherColor = Color.Blue.ToString();
});
I would write a foreach loop instead though:
var itemsToChange = objFreecusatomization.AllCustomizationButtonList
.Where(p => p.CategoryID == btnObj.CategoryID
&& p.IsSelected
&& p.ID == btnObj.ID);
foreach (var item in itemsToChange)
{
item.BtnColor = Color.Red.ToString();
item.OtherColor = Color.Blue.ToString();
}
(You can inline the query into the foreach statement itself, but personally I find the above approach using a separate local variable clearer.)