Let's say that I have the following function...
private List<QueryObject> ReturnSQLData (DateTime d1, DateTime d2, string[] arrayOfNames)
{
var results = (from a in _context.Names
where (a.CreatedOn >= d1 && a.CreatedOn <d2)
select new QueryObject
{
FirstName = a.Name
LastName = a.LastName
}).ToList();
return results;
}
How could I continue create a Linq query where I have something line this?
private List<QueryObject> ReturnSQLData (DateTime d1, DateTime d2, string[] arrayOfNames)
{
var results = (from a in _context.Names
where (a.CreatedOn >= d1 && a.CreatedOn <d2)
&& (arrayOfNames[0].Equals("abc") || arrayOfNames[1].Equals("cde")
select new QueryObject
{
FirstName = a.Name
LastName = a.LastName
}).ToList();
return results;
}
Note that I don't really know the size of the string[] until I am actually executing the code. How could I then add this statement on my linq query?
> && (arrayOfNames[0].Equals("abc") || arrayOfNames[1].Equals("cde") ||
> ... || arrayOfNames[n].Equals("cde"))
Would that be possible?
BTW. I am running this on a ASP.NET 5 MVC6 EF7 solution in case it helps :)
Thanks!
can you do:
&& arrayOfNames.Contains("cde")
Related
I have following Linq query. What I want is if I do search for a particular year, I should get corresponding records of that year. Else just show records of current year. Same way searchtext has also to be done.
public ActionResult Search(string searchtext, int? year)
{
string selyear = year.ToString();
string curyear = (DateTime.Now.Year).ToString();
hdms = from t in db.HOLIDAY
where
(year == null || t.DOH.StartsWith(selyear)) &&
(searchtext == "" || t.HOLIDAY_NAME == searchtext)
select new HOLIDAYDETAILS
{
DOH = t.DOH,
};
....
}
I want to satisfy this also if (year == null) then t.DOH.StartsWith(curyear) and
if (searchtext == "") then t.HOLIDAY_NAME != "Sunday" && t.HOLIDAY_NAME != "Saturday".
Also If both are null at the same time, both conditions should be satisfied together.
How can I give this one too on the above where clause?
If checking year is null or not is your problem then you simply can do like this-
public ActionResult Search(int? year)
{
string selyear = year.ToString();
string queryyear = (string.IsNullOrEmpty(selyear)) // checking for null
? (DateTime.Now.Year).ToString() // current year
: selyear; // year in query
hdms = from t in db.HOLIDAY
join t1 in db.EMPLOYEE on t.UPDATED_BY equals t1.EMP_CODE
where
t.DOH.StartsWith(queryyear) // comparing queryyear
orderby
t.DOH
select new HOLIDAYDETAILS
{
DOH = t.DOH,
};
....
}
Hope this will works for you...
public ActionResult Search(int? year)
{
string curyear = (DateTime.Now.Year).ToString();
string selyear = year!=null? year.ToString() : curyear;
var query = from t in db.HOLIDAY
join t1 in db.EMPLOYEE on t.UPDATED_BY equals t1.EMP_CODE
select new {t,t1};
query = query.Where(o=>o.t.DOH.StartsWith(selyear));
if (searchtext == "")
{
query = query.Where(o=>o.t.HOLIDAY_NAME != "Sunday" && o.t.HOLIDAY_NAME != "Saturday");
}
hdms = query.OrderBy(o=>o.t.DOH).Select(o=> new HOLIDAYDETAILS
{
DOH = o.t.DOH,
});
....
}
Hi i'm trying to convert this SQL script in Linq expression
but i donĀ“t know how do the MAX method in Linq
someone can help me?
thank you!
SELECT c.Nome,
c.NumeroRG,
f.Tipo,
f.Descricao,
f.DataHora,
f.IdCliente,
c.IdCliente,
f.IdFrequencia
FROM Cliente c, Frequencia f
WHERE f.Tipo = 1
AND c.IdCliente = f.IdCliente
AND cast(f.DataHora as date) = cast(getdate() as date)
AND f.IdFrequencia = (select MAX(fr.IdFrequencia)
from frequencia fr
where fr.IdCliente =c.IdCliente)
Perhaps something like this:
var query = from client in db.Cliente
join freq in db.Frequencia
on client.IdCliente equals freq.IdCliente
where freq.Tipo == 1
&& freq.DataHora.Date == DateTime.Now.Date
&& freq.IdFrequencia == db.Frequencia.Where(f => f.IdCliente == client.IdCliente)
Max(f => f.IdFrequencia)
select new { .... };
Maybe you need to replace DateTime.Now.Date/DateTime.Today with SqlFunctions.DatePart if you use LINQ-To-Entities, but you haven't mentioned that.
this worked well! thanks
var query = from client in db.Cliente
join freq in db.Frequencia
on client.IdCliente equals freq.IdCliente
where freq.Tipo == true
&& freq.DataHora.Value.Date == DateTime.Today.Date
&& freq.IdFrequencia == db.Frequencia.Where(f => f.IdCliente == client.IdCliente).Max(f => f.IdFrequencia)
select new { Nome = client.Nome, Descricao = freq.Descricao };
I have Table HR_Travel(TravelID, TravelCode....) and HR_TravelDocuments(TravelDocID, TravelID, DocUrl)
FromDate = FromDate.AddDays(1);
ToDate = ToDate.AddDays(1);
List<dynamic> Lst = new List<dynamic>();
var queryTravelDetails = from t in db.HR_TravelDetails
where ((t.StatusDate >= FromDate && t.StatusDate <= ToDate)
&& (t.EmpID == EmpID || EmpID == 0) && (t.TravelStatus == TravelStatus || TravelStatus == "All"))
orderby t.StatusDate descending
select new
{
TravelID = t.TravelID,
TravelSubID = db.HR_TravelDetails.Where(i => i.TravelID == 0).FirstOrDefault().TravelID == null ? 0 : db.HR_TravelDetails.Where(i => i.TravelID == 0).FirstOrDefault().TravelID,
t.TravelCode,
t.EmpID,
EmpName = db.EE_Employee.Where(i => i.EmpID == t.EmpID).FirstOrDefault().EmpName,
t.CellNo,
t.BoardingForm,
t.DestinationTO,
t.JournyDate,
t.Purpose,
t.Organization,
t.TravelStatus,
DocUrl = DocUrl = string.Join(",",( db.HR_TravelDocuments.Where(i => i.TravelID == t.TravelID && i.TravelSubID == 0).Select(i => i.DocUrl).ToList()))
};
foreach (var element in queryTravelDetails)
{
Lst.Add(element);
}
Gives the following error:
LINQ to Entities does not recognize the method 'System.String Join[String](System.String, System.Collections.Generic.IEnumerable`1[System.String])' method, and this method cannot be translated into a store expression.
The Join() method can't be used in LINQ expressions, because it cannot translate from CLR to T-SQL. Another example is that you can't use:
var itemCount = db.Table.Count(p => p.Something == SomeFunction(someVariable));
You should move the method call outside the LINQ statement:
var anotherVariable = SomeFunction(someVariable);
var itemCount = db.Table.Count(p => p.Something == anotherVariable);
I hope I explained in a good way.
EDIT: As seen in the comments before, you can also use ToArray() and when the data is loaded locally you can use functions in statements freely.
I have the following controller code that returns a Json list object to my view that draws a pie chart.
There are 4 input parameters and i have it working with 3 of them.
However, the fist parameter entitled 'SiteTypeId' needs to be included in the where.
My problem is how to include this neatly in the code, i'd like to avoid an override of the function.
The required additional logic is:
if SiteTypeId = -1 (then this means show all so nothing is to be changed)
if SiteTypeId = 0 (then i.SiteTypeId == 0 needs to be added)
if SiteTypeId = 1 (then i.SiteTypeId == 1 needs to be added)
If 2 and 3 above were all that was required it would be easy I guess. I'm thinking there must be a neat expression for this or a neat way of splitting the LINQ into 2 with a condition perhaps.
I'm new to LINQ - can anyone advise me, here is the controller code i need to modify:
public JsonResult GetChartData_IncidentsBySiteStatus(string SiteTypeId, string searchTextSite, string StartDate, string EndDate)
{
if (searchTextSite == null)
searchTextSite = "";
DateTime startDate = DateTime.Parse(StartDate);
DateTime endDate = DateTime.Parse(EndDate);
var qry = from s in _db.Sites
join i in _db.Incidents on s.SiteId equals i.SiteId
where s.SiteDescription.Contains(searchTextSite)
&& (i.Entered >= startDate && i.Entered <= endDate)
group s by s.SiteStatus.SiteStatusDescription + "[" + s.SiteTypeId.ToString() + "]"
into grp
select new
{
Site = grp.Key,
Count = grp.Count()
};
return Json(qry.ToList() , JsonRequestBehavior.AllowGet);
}
Sounds like you could use LINQKit and its PredicateBuilder. You use it to build dynamic conditional WHERE clauses. It's also used in LinqPad, and it's free.
Try this:
public JsonResult GetChartData_IncidentsBySiteStatus(string SiteTypeId, string searchTextSite, string StartDate, string EndDate)
{
if (searchTextSite == null)
searchTextSite = "";
DateTime startDate = DateTime.Parse(StartDate);
DateTime endDate = DateTime.Parse(EndDate);
var incidentsQry = _db.Incidents;
if(SiteTypeId > -1)
{
incidentsQry = incidentsQry.Where(a=>a.SiteTypeId == SiteTypeId);
}
var qry = from s in _db.Sites
join i in incidentsQry on s.SiteId equals i.SiteId
where s.SiteDescription.Contains(searchTextSite)
&& (i.Entered >= startDate && i.Entered <= endDate)
group s by s.SiteStatus.SiteStatusDescription + "[" + s.SiteTypeId.ToString() + "]"
into grp
select new
{
Site = grp.Key,
Count = grp.Count()
};
return Json(qry.ToList() , JsonRequestBehavior.AllowGet);
}
Simply add the following to your where clause
(SiteTypeId == -1 || i.SiteTypeId == SiteTypeId)
string NewsFillter = string.Empty;
List<string> PublishDatePostMeta = (from post in postrepository.GetAllPosts()
join pstmt in postrepository.GetAllPostMetas()
on post.int_PostId equals pstmt.int_PostId
where (post.int_PostTypeId == 4 && post.int_PostStatusId == 2 && post.int_OrganizationId == layoutrep.GetSidebarDetailById(SidebarDetailsId).int_OrganizationId) && pstmt.vcr_MetaKey=="Publish Date"
select pstmt.vcr_MetaValue).ToList();
int DatesCount = PublishDatePostMeta.Count();
foreach (string PublishDate in PublishDatePostMeta)
{
if (PublishDate != "")
{
NewsFillter += System.DateTime.Now + ">=" + Convert.ToDateTime(PublishDate);
}
}
var postsidebar = from post in postrepository.GetAllPosts()
join pstmt in postrepository.GetAllPostMetas()
on post.int_PostId equals pstmt.int_PostId
where (post.int_PostTypeId == 4 && post.int_PostStatusId == 2 && post.int_OrganizationId == layoutrep.GetSidebarDetailById(SidebarDetailsId).int_OrganizationId)
&& (pstmt.vcr_MetaKey.Contains(filter) && pstmt.vcr_MetaValue.Contains("true"))
select post;
1st question .The thing is that how NewsFillter would be accomdated in the postsidebar query in the pstmt object after true ( i would be putting it in contains,equals join or what) .
2nd question . is there any way that a chunk (between &&s) return enumerable and i can get away with this. at this moment it is not allowing that
I haven't udnerstood you properly, but if you want to apply multiple filters, here is my solution:
//Book is a table in the database
List<Expression<Func<Book, bool>>> filters = new List<Expression<Func<Book, bool>>>();
IQueryable<Book> query = dc.Books;
filters.Add(b => b.BookId == long.Parse(id));
//apply all filters
foreach (var f in filters)
query = query.Where(f);
Your questions:
This question requires an example of input and output. Try something like this:
|| pstmt.vcr_MetaKey=="Publish Date" && (
pstmt.vcr_MetaValue == "" || DateTime.Parse(pstmt.vcr_MetaValue) < DateTime.Now)
There is method AsEnumerable, if you mean what I think.