Lost with LINQ and Expressions - linq

I'm trying to write a LINQ query on some objects where I need to only do a select if a filter value is set.
Is there a way to "change" the query dynamically to only do a select if this is set.

Use where to find the items of interest, e.g.:
collection.Where(i => PassesFilter(i)).Select(i => i.InterestingValue);

var query = Somthing().Where(x => x.IsSomethingYouAlwaysFilterBy);
if(FilterValueIsSet(filterValue))
{
query = query.Where(x => x.Property == filterValue)
}

I'm not sure I understand your question, but you can use predicate builder. Predicate Builder example here

Related

Convert linq expression from method syntax to query syntax

Well I've got a query
var grouped = from a in query
group a.Payment by a.PaymentRecieverId
into g
select g;
query is a IQueryable of new { Payment payment, int PaymentRecieverId }
How can I convert this method expression to query?
If I understand correctly, the question is how to map group a.Payment part.
The GroupBy method has several overloads, you need the one that allows you to specify elementSelector:
var grouped = query.GroupBy(a => a.PaymentRecieverId, a => a.Payment);
If you mean lambda syntax, then it will be:
var grouped = query.GroupBy(x => x.PaymentRecieverId);
If you mean SQL query, then just hover your mouse on query object while debugging:

LinqKit PredicateBuilder adding to linq query

I have a linq query which I want to add some additional, optional WHERE conditions to using LinqKit Predicate Builder. However, I an struggling to get the additional predicate to work
This is my initial query:
var query = (from OP in ctx.OrganisationProducts
where OP.OrganisationID == orgID
orderby OP.Product.Name, OP.Product.VersionName
select OP).Include("Product");
As you can see, there is JOIN in there.
I then wish to add additional predicates if required:
if(!includeDisabledP42Admin || !includeDisabledOrgAdmin)
{
var pred = PredicateBuilder.True<OrganisationProduct>();
if (!includeDisabledP42Admin)
pred.And(op => op.Enabled);
if (!includeDisabledOrgAdmin)
pred.And(op => op.AccessLevel == "NA" || op.AccessLevel == "NU");
query = query.Where(pred);
}
However, the generated SQL is unchanged and the query returns the same number of rows.
I thought I might have had to do the Expand conversion as so:
query = query.AsExpandable().Where(pred);
But this causes a runtime error.
I think the issue is the fact that I am adding the predicate to a query that is already no longer a pure OrganisationProduct object, however I would like advise on how I insert my predicate at the right place.
Thanks and all :-)
You have to assign the return value of And to the predicate:
pred = pred.And(op => op.Enabled);
Side note: you may like this predicate builder that works without Expand/AsExpandable, but has the same syntax.

Linq convert a Method Syntax to Query Expression

Recently I wrote this query with Linq (Method Syntax), notes:
g.CmsContents is a Navigatiola Property.
I would like to know how to rewrite this code as a Linq Query Expression if it is possible.
var myGroupsTypesList = from g in context.CmsGroupsTypes
where g.CmsContents.Any(x => x.ContentId == myContentId)
select g;
Any idea? Thanks for your support :-)
That's already a query expression. If you mean you want to convert the Any part to another query expression - you can't. There's no query expression support for Any.
If you actually meant it the other way round, your query is equivalent to:
var myGroupsTypesList = context.CmsGroupsTypes
.Where(g => g.CmsContents.Any(x => x.ContentId == myContentId));

How do I merge two LINQ statements into one to perform a list2.Except(list1)?

Currently, I have the following LINQ queries. How can I merge the two queries into one. Basically, write a LINQ query to bring back the results I'd get from
IEnumerable<int> deltaList = people2010.Except(allPeople);
except in a single query.
var people2010 = Contacts.Where(x => x.Contractors
.Any(d => d.ContractorsStatusTrackings
.Any(date => date.StatusDate.Year >= 2010)))
.Select(x => x.ContactID);
var allPeople = Contacts.Where(x => x.Contractors
.Any(m => m.ContactID == x.ContactID))
.Select(x=> x.ContactID);
Thanks!
Why can you not just do Except as you are doing? Don't forget that your people2010 and allPeople variables are just queries - they're not the data. Why not just use them as they are?
If that's not acceptable for some reason, please give us more information - such as whether this is in LINQ to Object, LINQ to SQL etc, and what's wrong with just using Except.
It sounds like you're just looking for a more elegant way to write your query. I believe that this is a more elegant way to write your combined queries:
var deltaList =
from contact in Contacts
let contractors = contact.Contractors
where contractors.Any(ctor => ctor.ContractorStatusTrackings
.Any(date => date.StatusDate.Year >= 2010))
&& !contractors.Any(m => m.ContactID == contact.ContactID)
select contact.ContactID

Limiting fields returned in a LINQ query

A few days ago I asked a question about returning select fields from a LINQ query. Now, I want to add some grouping to the results and things are not working out.
The following query returns the correct rows but I want to limit the fields returned. For example, I only want to see the Id and Name fields.
var contactsFromDealers = Contacts.Where(x => x.ContactTypeID == 2).GroupBy (x => x.OrganizationName)
and appending .Select (x => x.Id, x.OrganizationName) doesn't help.
Any suggestions? Thanks!
you need the select before the group by i believe.
try .Select( x => new { x.Name } )

Resources