Linq query Contains - c#

i have an issue with this query
var myList = (from p in db.Full
where (p.date_reception > begin & p.date_reception < end
& !p.mc_owner.Contains("NULL") & !p.mc_owner.Contains(""))
group p by p.mc_owner into g
orderby g.Count() descending
select new
{
Ownerx = g.Key,
countx = g.Count()
}).ToList();
Everything works well without adding !p.mc_owner.Contains(""), but once i do it just shows no results

Any string with value will contain empty string. For example next testcode will print true.
string a = "abc";
Console.WriteLine(a.Contains(""));
Console.ReadLine();
You probably meant to write:
p.mc_owner != ""
or it is better to write
!string.IsNullOrEmpty(p.mc_owner)
I guess with .contains("NULL") you wanted to leave out NULL values and not the string "NULL". Also I would && instead of &. I suggest to rewrite to:
(p.date_reception > begin && p.date_reception < end
&& !string.IsNullOrEmpty(p.mc_owner))

The way I would do this is:
var myList = (from p in db.Full
where (p.date_reception > begin & p.date_reception < end
& !p.mc_owner.Contains("NULL") & !string.IsNullOrWhiteSpace(p.mc_owner))
group p by p.mc_owner into g
orderby g.Count() descending
select new
{
Ownerx = g.Key,
countx = g.Count()
}).ToList();

Related

Conditional retrieval of data through linq in C#

var Getdetails = (from p in XYZDb.tblPulls
join
ro in XYZDb.tblRentalOrders
on p.AffCode equals ro.AffCode.Value
join
tpsb in XYZDb.tblPullSheetBatchProcessings
on p.PullNo.ToString() equals tpsb.PullSheet
select new
{
PullNos = p.PullNo,
AffCode = p.AffCode,
TotalItems = p.TotalItems,
p.PostedOn,
p.UpdatedOn,
p.IsPrinted,
BatchName = tpsb.BatchName
})
.Where(i => i.PostedOn >= from_date && i.PostedOn <= to && i.IsPrinted != null).Distinct();
In the above code only the pullno having BatchName are coming, i want to retrieve all the pullno within that timezone, and if it is batched, then the BatchName will also appear. I am stuck on that. Any kind of help will be appreciated. Feel free to ask any question.
Use left outer join,
var Getdetails = (from p in XYZDb.tblPulls
join
ro in XYZDb.tblRentalOrders
on p.AffCode equals ro.AffCode.Value
join
tpsb in XYZDb.tblPullSheetBatchProcessings
on p.PullNo.ToString() equals tpsb.PullSheet into pt
from batch in pt.DefaultIfEmpty()
select new
{
PullNos = p.PullNo,
AffCode = p.AffCode,
TotalItems = p.TotalItems,
p.PostedOn,
p.UpdatedOn,
p.IsPrinted,
BatchName = (batch == null ? String.Empty : batch.BatchName )
})
.Where(i => i.PostedOn >= from_date && i.PostedOn <= to && i.IsPrinted != null).Distinct();

LINQ Query to Filter then to a Model

How can I do this correctly?
This is failing because schedule-on does not exist within m from RR2.
var RR = (from m in DataContext.csrcallds
where m.scheduledon >= earliestDate
&& m.scheduledon <= objdate1.DateStart
&& m.assignto == 113
&& (SqlMethods.DateDiffDay(m.scheduledon, m.completedon) > 5)
select m
);
var RR2 = RR.Select(x => (GetBusinessDays((DateTime)x.scheduledon, (DateTime)x.completedon)) > 5).ToList());
var RnR = (from m in RR2
group m by new { m.scheduledon.Value.Year, m.scheduledon.Value.Month } into p
orderby p.Key.Year ascending, p.Key.Month ascending
select new Date1()
{
theDate = DateTime.Parse($"{p.Key.Month} - {p.Key.Year}"),
theCount = p.Count(),
theString = $"{p.Key.Month} - {p.Key.Year}"
});
I am trying to query all the results.
Then use my GetBusinessDay function to filter out the ones I don't need, gathering only the records within 5 business days.
Then put the results into my Model named Date1.
I'm trying to do it like this because I cannot use GetBusinessDays within an LINQ query.
So I'm trying to filter it outside of SQL, then group the records again.
How do I go about accomplishing this task?
You could add this to your SQL Query to filter out the weekend days.
SELECT *
FROM your_table
WHERE ((DATEPART(dw, date_created) + ##DATEFIRST) % 7) NOT IN (0, 1)
Or This
select [date_created]
from table
where DATENAME(WEEKDAY, [date_created]) <> 'Saturday'
and DATENAME(WEEKDAY, [date_created]) <> 'Sunday'
Or if you have to stick to LINQ try the ideas outlined here:
Linq query DateTime.Date.DayOfWeek
DateTime firstSunday = new DateTime(1753, 1, 7);
var bookings = from b in this.db.Bookings
where EntityFunctions.DiffDays(firstSunday, b.StartDateTime) % 7 == 1
select b;
Solved by using function workdays server side:
https://stackoverflow.com/a/252532/6157660
Allows me to make a simple LINQ query, and gives me what I need.
I did edit the function to remove the +1 from DateDiff. as same days should be 0 not 1.
Thank you guys for your help!
var RnR = (from m in DataContext.csrcallds
where m.scheduledon >= earliestDate
&& m.scheduledon <= objdate1.DateStart
&& m.assignto == 113
&& (DataContext.fn_WorkDays((DateTime)m.scheduledon, (DateTime)m.completedon)) > 5
group m by new { m.scheduledon.Value.Year, m.scheduledon.Value.Month } into p
orderby p.Key.Year ascending, p.Key.Month ascending
select new Date1()
{
theDate = DateTime.Parse($"{p.Key.Month} - {p.Key.Year}"),
theCount = p.Count(),
theString = $"{p.Key.Month} - {p.Key.Year}"
});

Entity framework average , group by query

Hello i have the following query
var myList = (from p in db.Full
where (p.date_reception > begin & p.date_reception < end & !p.mc_object.Contains("NULL")
& (!strListe.Contains(p.mc_object)))
group p by new { p.mc_object} into g
select g.OrderByDescending(p => new {p.duration,p.mc_object} ) into r
select new StringIntType
{
str = r.mc_object,
nbr = r.duration.Value
}).Take(50).ToList();
I need to group by mc_object , and select mc_object , average of duration
and order by average of duration descending ,Thank you for helping
The query should be
var myList = (from p in db.Full
// Don't use &! Use &&
where p.date_reception > begin &&
p.date_reception < end &&
!p.mc_object.Contains("NULL") &&
!strListe.Contains(p.mc_object)
group p by p.mc_object into g
select new
{
mc_object = g.Key,
/* data = g, */
avg = g.Average(x => x.duration)
} into h
// if you want both descending, add descending after mc_object
orderby h.avg descending, h.mc_object
select new StringIntType
{
str = h.mc_object,
nbr = (int)h.avg // Average returns a double
}).Take(50).ToList();
}
Note that I've changed the & to &&. For the ordering I wasnt sure. I dont need the full data in the second half of the query, so I've added a commented data = g

Entity framework linq query

I have this piece of code. What i need to do is to exclude mc_host_class values that are inside the list.
enter var myList = (from p in db.Full
where ( (p.date_reception > begin & p.date_reception < end & !p.mc_host_class.Contains("NULL")) &
( !p.mc_host_class.Contains( (
from p2 in db.exclure
where (p2.type.Contains("Host"))
group p2 by p2.libelle into g
select new { libellex = g.Key}).ToList()
)))
group p by p.mc_host_class into g
orderby g.Count() descending
select new
{
hostclassx = g.Key,
countx = g.Count()
}).ToList().Take(10);
Thank you for helping
If I understood your question, I think this could help you:
(!(
from p2 in db.exclure
where (p2.type.Contains("Host")
group p2 by p2.libelle into g
select new { libellex = g.Key}
).ToList().Contains(p.mc_host_class))
List1.Contains(value1) return a bool if a value1 is in List1, but you used it like value1.Contains(List1).

left join linq when right list is empty

pdlist = (from a in context.EMPLOYEES
join b in context.PERSONS on a.PERSON_ID equals b.PERSON_ID
where a.SUPERVISOR_ID == empId
select new Pollidut.Models.Pollidut
{
PollidutId = a.EMPLOYEE_ID,
PollidutName = b.PERSON_NAME,
DistributionHouseId = a.DISTRIBUTION_HOUSE_ID == null ? 0 : (int)a.DISTRIBUTION_HOUSE_ID
}).ToList();
DateTime dt = DateTime.Now.Date;
var pdTargets = (from p in context.PALLYDUT_TARGET
where p.Active == true && p.StartDate <= dt && p.EndDate >= dt
group p by p.PallydutId into g
select new
{
PollidutId = g.Key,
Start = g.Select(x => x.StartDate).Min(),
End = g.Select(y => y.EndDate).Max(),
Target = g.Select(z => z.Target).Sum()
}).ToList();
var PdTargetsList = (from m in pdlist
join n in pdTargets on m.PollidutId equals n.PollidutId into t
from l in t.DefaultIfEmpty()
select new
{
PallydutId = m.PollidutId,
PallydutName = m.PollidutName,
DistributionId = m.DistributionHouseId,
StartDate = l.Start == null ? dt : l.Start,
EndDate = l.End == null ? dt : l.End,
Target = l.Target == null ? 0 : l.Target
}).ToList();
pdlist is employee list where pdTarget may set or not. pdTarget can be empty. When I left join pdlist with pdTargets I get Object reference not set error. pdTargets collection returns null.How to fix it. Anybody helps me greatly appreciated.
The reason I suspect why you are getting a Null reference exception is because your are directly accessing the properties on a null object (l in your case), even though you are using a DefaultIfEmpty() method which is going to return null if no matching rows are found. You should change your code like this:-
select new
{
PallydutId = m.PollidutId,
PallydutName = m.PollidutName,
DistributionId = m.DistributionHouseId,
StartDate = l == null ? dt : l.Start,
EndDate = l == null ? dt : l.End,
Target = l == null ? 0 : l.Target
}).ToList();
Also, If you think that your one object pdTarget can be null, then I don't think its about a left join or a normal join, your code will throw an exception in either case. Please check this MSDN documentation to handle nulls in query expressions.

Categories

Resources