Dynamic where condition in linq query expression - linq

My Code :
IEnumerable<DataRow> whrRowEnum;
whrRowEnum = from r in dtInput.AsEnumerable()
where r.Field<string>("EMP_DEP") == "DEP1"
orderby EMP_DEP
select r;
The above code is working fine due to hard coded where condition, but In run-time I need to add multiple where condition in my linq query like r.Field("EMP_DEP") == "DEP1" && r.Field("EMP_ID") == "EMP1"

You can use lambda syntax to compose your query based on conditions:
IEnumerable<DataRow> query = dtInput.AsEnumerable();
if (condition1)
query = query.Where(r => r.Field<string>("EMP_DEP") == "DEP1");
if (condition2)
query = query.Where(r => r.Field<string>("EMP_ID") == "EMP1");
var whrRowEnum = query.OrderBy(r => r.Field<string>("EMP_DEP"));
Another option is adding conditions to query filter
whrRowEnum = from r in dtInput.AsEnumerable()
where (!condition1 || (r.Field<string>("EMP_DEP") == "DEP1")) &&
(!condition2 || (r.Field<string>("EMP_ID") == "EMP1"))
orderby EMP_DEP
select r;

Related

LINQ EF AND VS2017

I wrote a query and worked on LINQPAD
from x in FacilityData
from y in FavInformation
where y.UserID == 1 && x.ID == y.FacilityID
select new
{
xID = x.ID,
xDistrictName = (from y in _Ilcelers
where y.ID == x.DistrictID
select y.IlceAd).FirstOrDefault(),
xName = x.Name,
Value = (from o in Tags
from p in Table_tags
where o.Prefix != null && o.Prefix == p._NAME && o.Facility == y.FacilityID
orderby p.İd descending
select new
{
FType = o.TagType,
Name = o.TagsName,
Value = p._VALUE,
Time = p._TIMESTAMP
}).Take(Tags.Count(h => h.Facility == y.FacilityID))
}
result
the result is perfect
but does not work in visual studio,
Value = (from o in DB.Tags
from p in DB.table_tags
where o.Prefix != null && o.Prefix == p.C_NAME && o.Facility == 11
orderby p.id descending
select new
{
FType=o.TagType,
Name = o.TagsName,
Value = p.C_VALUE,
Time = p.C_TIMESTAMP
}).Take(Tags.Count(h => h.Facility == y.FacilityID))
and it gives an error.
I guess the part with .Take() doesn't work because it's linq to EF.
error:
Limit must be a DbConstantExpression or a Db Parameter Reference Expression. Parametre name: count]
error image
thank you have a good day
Not sure but I will just throw it in. If you are talking about linq to ef/sql, it is possible they dont know a thing about C#. If take() would be the problem try to get the select result local first by doing .tolist(). Afterwards use your take funtion.
.ToList().Take(Tags.Count(h => h.Facility == y.FacilityID))

How to compare IEnumerable<string> for null in Linq query

For the following query:
var result = from sch in schemeDashboard
join exp in Expenditure on sch.schemeId equals exp.SchemeCode
into SchExpGroup
where sch.SectorDepartmentId == selectedDepartmentId &&
sch.YearCode == StateManager.CurrentYear
orderby sch.ADPId
select new
{
ModifiedAmounts = SchExpGroup.Select(a => a.ModifiedAmounts),
ProjectName = sch.schemeName,
ADPNo = sch.ADPId,
Allocation = sch.CurrentAllocation,
Expenditures = from expend in SchExpGroup
where expend.YearCode == StateManager.CurrentYear &&
expend.DepartmentId == selectedDepartmentId &&
InvStatus.Contains(expend.Status)
orderby expend.ADPId
group expend by expend.InvoiceId
};
I want to filter the above query on a condition so that result gives only those records where "ModifiedAmounts" are not null. I have tried as follow:
if (rbList2.SelectedIndex == 6)
{
result = result.Where(a => a.ModifiedAmounts != null));
}
but this gives error as:
Cannot compare elements of type
'System.Collections.Generic.IEnumerable`1'. Only primitive types,
enumeration types and entity types are supported.
Any suggestions as I am lost as how to rephrase the filtered query.
I think the problem is that ModifiedAmounts will never be null. Select will return an empty list. Unless SchExpGroup is null in which case you will get a null reference exception.
Try changing your code to
result = result.Where(a => a.ModifiedAmounts.Any());
if (rbList2.SelectedIndex == 6)
{
result = result.Where(a => a.!ModifiedAmounts.Any());
}

Dynamic where condition LINQ

I have a problem with my code. I don't know how I can insert in my selection all equals conditions of:
codicielementipartizione.sezione == el[i].ToString()
dynamically from
codicielementipartizione.sezione == el[1].ToString()
to
codicielementipartizione.sezione == el[el.count - 1].ToString()
Tn this code:
var selection = (from codicielementipartizione inlistacodici.cep
where codicielementipartizione.uno == 1 &&
codicielementipartizione.sezione == el[i].ToString()
select codicielementipartizione).ToList();
You can make the fixed part of the query which will be IQueryable. After that you can add your conditions as such.
Fixed part:
var query = from codicielementipartizione in listacodici.cep
where codicielementipartizione.uno == 1;
Dynamic part:
foreach(var condition in el)
query = query.Where(codicielementipartizione.sezione == el.ToString());
Query execution:
var result = query.Select().ToList();
Maybe you mean this:
var selection = (from codicielementipartizione in listacodici.cep
where codicielementipartizione.uno == 1
&& el.Select(i => i.ToString()).Contains(codicielementipartizione.sezione)
select codicielementipartizione).ToList();

Hide Join if string.IsNullOrEmpty using Linq

I got this linq query which searches for selected values in my database using dropdowns.
Is there a way to hide the "join" in the linq query if the ddlCategory is null? I want this because the result of the search shows duplicated-rows because my documents can have many Categories.?? hope you understand what i mean.. Can anyone help??
var documents = from d in data.tblDocuments
join sc in data.tblSubCategories on d.DocId equals sc.DocId
orderby d.Docyear descending
where
(string.IsNullOrEmpty(person) || d.DocPerson.Equals(person)) &&
(string.IsNullOrEmpty(year) || d.Docyear.Equals(year)) &&
(string.IsNullOrEmpty(law) || d.DocLaw.Equals(law)) &&
(string.IsNullOrEmpty(court) || d.DocCourt.Equals(court)) &&
(string.IsNullOrEmpty(category) || sc.CategoryId.Equals(category)) &&
(string.IsNullOrEmpty(casenr) || d.DocNr.Equals(casenr))
select d;
Use lambda syntax:
var query = data.tblDocuments;
if (condition) // conditionally add join
query = query.Join(data.tblSubCategories.Where(sc => sc.CategoryId == category),
d => d.DocId, sc => sc.DocId, (d,sc) => d);
// continue to compose query
query = query.OrderByDescending(d => d.Docyear)
.Where(d => ...);
BTW you can compose filtering based on conditions:
if (!String.IsNullOrEmpty(person))
query = query.Where(d => d.DocPerson == person);

Distinct keyword in linq query

my linq query returns duplicate records like below, how i have to use distinct keyword in this linq query.
var draft_recieved = from df in _DataContext.tblDrafts
from dfBody in _DataContext.DraftBodies
from sendUser in _DataContext.tblSends
where (df.DraftId == dfBody.DraftID) && (df.DraftId == sendUser.DraftId) &&
(sendUser.ToEmailId == (Guid)Membership.GetUser().ProviderUserKey)
select new
{
subject = dfBody.Subject,
draftid = df.DraftId
};
.Distinct() has to be applied as an extension method.
var draft_recieved = (from df in _DataContext.tblDrafts
from dfBody in _DataContext.DraftBodies
from sendUser in _DataContext.tblSends
where (df.DraftId == dfBody.DraftID) && (df.DraftId == sendUser.DraftId) &&
(sendUser.ToEmailId == (Guid)Membership.GetUser().ProviderUserKey)
select new
{
subject = dfBody.Subject,
draftid = df.DraftId
}).Distinct();

Resources