This question already has answers here:
linq case statement
(6 answers)
Closed 8 years ago.
how can I translate this into LINQ?
select t.age as AgeRange, count(*) as Users
from (
select case
when age between 0 and 9 then ' 0-25'
when age between 10 and 14 then '26-40'
when age between 20 and 49 then '60-100'
else '50+' end as age
from user) t
group by t.age
Thank you!
Maybe this works:
from u in users
let range = (u.Age >= 0 && u.Age < 10 ? "0-25" :
u.Age >= 10 && u.Age < 15 ? "26-40" :
u.Age >= 15 && u.Age < 50 ? "60-100" :
"50+")
group u by range into g
select new { g.Key, Count=g.Count() };
check this may help you
var query = from grade in sc.StudentGrade
join student in sc.Person on grade.Person.PersonID
equals student.PersonID
select new
{
FirstName = student.FirstName,
LastName = student.LastName,
Grade = grade.Grade.Value >= 4 ? "A" :
grade.Grade.Value >= 3 ? "B" :
grade.Grade.Value >= 2 ? "C" :
grade.Grade.Value != null ? "D" : "-"
};
Use something like that:
class AgeHelper
{
private static Dictionary<IEnumerable<int>, string> dic = new Dictionary<IEnumerable<int>, string>
{
{ Enumerable.Range(0, 10), "0-25" },
{ Enumerable.Range(10, 5), "26-40" },
{ Enumerable.Range(15, 35), "60-100" }
};
public string this[int age]
{
get
{
return dic.FirstOrDefault(p => p.Key.Contains(age)).Value ?? "50+";
}
}
}
The rest of #Botz3000's answer:
from u in users
let range = new AgeHelper()[u.Age]
...
Something like this?
var users = (from u in Users
select new
{
User = u,
AgeRange =
u.Age >= 0 && u.Age <= 9 ? "0-25" :
u.Age <= 14 ? "26-50" :
u.Age <= 49 ? "60-100":
"50+"
}).GroupBy(e => e.AgeRange);
I don't know of any way how to create efficient SQL like this, using a LINQ statement. But you can use:
Use a stored procedure (or function), and call the stored procedure from LINQ.
Use Direct SQL
Sure you can use a lot of inline conditional statements (? :), but I don't think the result will be efficient.
Related
UPDATE m
SET m.Score = s.AScore + '-' + s.BScore
FROM #Matches m
INNER JOIN Scores s ON m.MatchId = s.MatchId
AND s.InfoTypeId = (
CASE
WHEN m.SportId = 1 AND (m.StatusId >= 13 AND m.StatusId <= 17) THEN 10
WHEN m.SportId = 1 AND m.StatusId = 20 THEN 24
WHEN m.SportId = 1 AND m.StatusId = 21 THEN 23
WHEN m.SportId = 1 AND m.StatusId = 18 THEN 8
ELSE 5
END
)
I'm having two lists in C# one is Matches and 2nd is Scores, and I want to get the result from those list like the result this query will return. Means I want to update "Score" property of "Matches" list like it is being updated in SQL query.
Any Help Please.
Matches.ForEach(m => m.Score = (Scores.Where(ms => ms.MatchId == m.MatchId
&& ms.ScoreInfoTypeId == ((m.SportId == 1 && m.StatusId >= 13 && m.StatusId <= 17) ? 10
: (m.SportId == 1 && m.StatusId == 20) ? 24
: (m.SportId == 1 && m.StatusId == 21) ? 23
: (m.SportId == 1 && m.StatusId == 18) ? 8
: 5)).Select(ms => ms.AScore + "-" + ms.BScore).FirstOrDefault()));
I have tried, but I think its too expensive. It is taking too much time. Is there any optimized way please.
Try this example in LinqPad. You can use query syntax to join the 2 lists and iterate over the result to set match scores. I used a dictionary to simplify that switch case.
void Main()
{
var matches = new[]{
new Match{MatchId=1,SportId=1,StatusId=13,Score=""},
new Match{MatchId=2,SportId=1,StatusId=18,Score=""},
new Match{MatchId=3,SportId=2,StatusId=24,Score=""},
};
var scores = new[]{
new{MatchId=1,AScore="10",BScore="0",InfoTypeId=10},
new{MatchId=2,AScore="20",BScore="0",InfoTypeId=8},
new{MatchId=3,AScore="30",BScore="0",InfoTypeId=5},
};
var dict = new Dictionary<int,int>{[13]=10,[14]=10,[15]=10,[16]=10,[17]=10,[20]=24,[21]=23,[18]=8};
var data = (from m in matches
join s in scores on m.MatchId equals s.MatchId
where s.InfoTypeId == ((m.SportId == 1 && dict.ContainsKey(m.StatusId))? dict[m.StatusId] : 5)
select new {m,s}
).ToList();
data.ForEach(o =>
{
o.m.Score = o.s.AScore + "-" + o.s.BScore;
});
matches.Dump();
}
class Match{public int MatchId; public int SportId; public int StatusId; public string Score;}
I have this query that was actually a view but I wanted to control the WHERE clause so I decided to tackle it by LINQ and EF6:
SELECT NULLIF(SUM([a].[REQUESTED_QTY]), 0) AS [Transaction],
NULLIF(SUM([a].[ITEM_TOTAL]), 0) AS [Income]
FROM [dbo].[BILL_INFO_DETAIL] AS [a]
INNER JOIN [dbo].[SERVICE_INFO] AS [b]
ON [a].[SERVICE_CODE] = [b].[SERVICE_CODE]
WHERE ([a].[INPUT_STATUS] = '1')
AND ([b].[SERVICE_CODE] IN ( 1610, 1611, 1612 ))
AND ([a].[PAY_MODE_ID] IN ( 1, 2 ))
AND (CONVERT(VARCHAR(2), a.STAMP_DATE, 101) IN ( '10', '11', '12' ))
AND (CONVERT(VARCHAR(4), a.STAMP_DATE, 102) IN ( '2017' ))
AND ([b].[FEE] > 1)
After a while of trial and error, I got this conversion:
public async Task<ViewGuessOnline> GetGuessOnline(int[] serviceCodes, byte[] payModes, string[] months, string year)
{
try
{
using (var context = new FinanceConnection())
{
var resultTemp = from a in
(from a in context.BILL_INFO_DETAILS
where
a.INPUT_STATUS == true &&
serviceCodes.Contains(a.SERVICE_INFO.SERVICE_CODE) &&
payModes.Contains(a.PAY_MODE_ID) &&
months.Contains(SqlFunctions.StringConvert(a.STAMP_DATE)) &&
(new[] {"2017"}).Contains(SqlFunctions.StringConvert(a.STAMP_DATE)) &&
a.SERVICE_INFO.FEE > 1
select new
{
a.REQUESTED_QTY,
a.ITEM_TOTAL,
Dummy = "x"
})
group a by new {a.Dummy}
into g
select new
{
Transaction = g.Sum(p => p.REQUESTED_QTY) == 0 ? (int?) null : (int) g.Sum(p => p.REQUESTED_QTY),
Income = g.Sum(p => p.ITEM_TOTAL) == 0 ? (decimal?) null : (decimal) g.Sum(p => p.ITEM_TOTAL)
};
// result = (await result.OrderByDescending(o => o.CustomerCode).ToListAsync()).AsQueryable();
}
Logger.Info($"{LayerName} -> {callerInfo.MethodName} -> Returning");
return result;
}
catch (Exception exp)
{
Logger.Error($"{LayerName} -> {callerInfo.MethodName} -> Exception [{exp.Message}]", exp);
throw;
}
}
I'm having an issue with the date part. In original SQL, the comparison of a Quarter 4 of 2107 is very easy. But I cannot find a proper inline linq conversion that translates to proper SQL.
Also, I had to use a dummy grouping even thoug there is not groups in the original SQL.
A bit more wall-baning and I was able to make this work:
from a in
(from a in db.BILL_INFO_DETAIL
where
a.INPUT_STATUS == true &&
(new int[] {1610, 1611, 1612 }).Contains(a.SERVICE_INFO.SERVICE_CODE) &&
(new int[] {1, 2 }).Contains(a.PAY_MODE_ID) &&
a.STAMP_DATE != null &&
(new int[] {10, 11, 12 }).Contains(a.STAMP_DATE.Value.Month) &&
a.STAMP_DATE.Value.Year == 2017 &&
a.SERVICE_INFO.FEE > 1
select new
{
a.REQUESTED_QTY,
a.ITEM_TOTAL,
Dummy = "x"
})
group a by new {a.Dummy}
into g
select new
{
Transaction = g.Sum(p => p.REQUESTED_QTY) == 0 ? (int?) null : (int) g.Sum(p => p.REQUESTED_QTY),
Income = g.Sum(p => p.ITEM_TOTAL) == 0 ? (decimal?) null : (decimal) g.Sum(p => p.ITEM_TOTAL)
}
I changed the method's parameter datatypes accordingly and this works now.
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}"
});
I need to select date and average values from a datacontext's table and I need to group it by year and by month.
In SQL it will look like this
select Year(data) as years, Month(data) as months, Avg(value) as prices from Prices
group by Year(data),MONTH(data)
order by years, months
I've created a LINQ query
var query0 = from c in dc.Prices
where Convert.ToDateTime(c.data).CompareTo(left) >= 0
&& Convert.ToDateTime(c.data).CompareTo(right) <= 0
&& c.idsticker.Equals(x)
group c by new { ((DateTime)c.data).Year, ((DateTime)c.data).Month }
into groupMonthAvg
select groupMonthAvg;
But I don't know how to get average values in result
Use the Average function.
var query0 = from c in dc.Prices
where Convert.ToDateTime(c.data).CompareTo(left) >= 0
&& Convert.ToDateTime(c.data).CompareTo(right) <= 0
&& c.idsticker.Equals(x)
group c by new { ((DateTime)c.data).Year, ((DateTime)c.data).Month }
into groupMonthAvg
select new
{
years = groupMonthAvg.Key.Year,
months = groupMonthAvg.Key.Month,
prices = groupMonthAvg.Average(x=>x.value)
};
Just use the Average function in your select:
var query0 = from c in dc.Prices
where Convert.ToDateTime(c.data).CompareTo(left) >= 0
&& Convert.ToDateTime(c.data).CompareTo(right) <= 0
&& c.idsticker.Equals(x)
group c by new { ((DateTime)c.data).Year, ((DateTime)c.data).Month }
into groupMonthAvg
select new {
groupMonthAvg.Key.Year,
groupMonthAvg.Key.Month,
YearAverage = groupMonthAvg.Average(x=>x.Year),
MonthAverage = groupMonthAvg.Average(x=>x.Month)
};
This should do it:
var query0 = from c in dc.Prices
where Convert.ToDateTime(c.data).CompareTo(left) >= 0
&& Convert.ToDateTime(c.data).CompareTo(right) <= 0
&& c.idsticker.Equals(x)
group c by new { ((DateTime)c.data).Year, ((DateTime)c.data).Month }
into groupMonthAvg
select new { Year = groupMonthAvg.Key.Year, Month = groupMonthAvg.Key.Month, Average => groupMonthAvg.Average(i => i.value) };
Take this example:
int[] queryValues1 = new int[10] {0,1,2,3,4,5,6,7,8,9};
int[] queryValues2 = new int[100]; // this is 0 to 100
for (int i = 0; i < queryValues2.Length; i++)
{
queryValues2[i] = i;
}
var queryResult =
from qRes1 in queryValues1
from qRes2 in queryValues2
where qRes1 * qRes2 == 12
select new { qRes1, qRes2 };
foreach (var result in queryResult)
{
textBox1.Text += result.qRes1 + " * " + result.qRes2 + " = 12" + Environment.NewLine;
}
Obviously this code will result in:
1 * 12 = 12
2 * 6 = 12
3 * 4 = 12
4 * 3 = 12
6 * 2 = 12
But what I need is only the first 3 lines. That is I do not want if 2*6 = 12 the query checks if 6*2 is also 12. Is there a way to filter this in the LINQ query or I have to do it in the foreach loop afterward?
My question just is a sample to show what I mean. so I want to know the way of doing such thing no matter what is the type of object being linqed to!
In general the simple solution would be more where conditions since the where clauses are what by definition cause LINQ to skip iterations:
var queryResult =
from qRes1 in queryValues1
from qRes2 in queryValues1
where qRes1 * qRes2 == 12
&& qRes1 <= Math.Sqrt(12)
select new { qRes1, qRes2 };
You could use .Distinct() and create your own IEqualityComparer that compares objects based on what 'equals' means in your case.
So, for your original example:
class PairSetEqualityComparer : IEqualityComparer<Tuple<int, int>>
{
public bool Equals(Tuple<int, int> x, Tuple<int, int> y)
{
return (x.Item1 == y.Item1 && x.Item2 == y.Item2) ||
(x.Item1 == y.Item2 && x.Item2 == y.Item1);
}
public int GetHashCode(Tuple<int, int> obj)
{
return obj.Item1*obj.Item2;
}
}
And, you use it like this:
var queryResult =
(from qRes1 in queryValues1
from qRes2 in queryValues2
where qRes1 * qRes2 == 12
select new Tuple<int, int>(qRes1, qRes2)).Distinct(new PairSetEqualityComparer());
TakeWhile(condition):Returns elements from a sequence as long as a specified condition is true, and then skips the remaining elements.
foreach (var result in queryResult.TakeWhile(x => x.qRes1 <= Math.Sqrt(12)))