Query objects, databases, and XML with expressive operators. Learn deferred execution, projections, grouping, joins, performance tips, and idiomatic LINQ patterns that make data code concise and powerful.
1,228 posts662 contributors
/****** Script for SelectTopNRows command from SSMS ******/ SELECT B.[LabId] ,[TrayNo] ,B.[BoxNo] ,B.[RackNo] ,M.id,M.Id FROM [BV_OCM].[dbo].[TblBatch] B INNER JOIN [BV_OCM].[dbo].[MstRackBox] M ON B.RackNo = M.RackNo and B.[BoxNo]=M.[BoxNo] where B.Id=85
Dear Team i have a mysql table like below id , firstname, lastname, location, dateofinterview and i using one dropdown , 1 textbox and two date field to search the result from db here the location is dropdown and i will always have a value greater than 0 in the db but in dropdown its default is 0 , the text box has to search any work like (contain) keyword in mysql from both firstname and last name and the two date column will search from date of interview column here lets say is the from date is empty then the from date should be negative 30 days from today and if to date is empty then the to date should be 30 days from today and if from and to are given the rows that matched between the dates should appear one more stopper : if location is not given then the matching values from other search criteria should appear i am trying to write it in linq and i am struck in the dropdown and the date part kindly help.
DECLARE @vDeptId INT SELECT Id ,CONVERT(NVARCHAR(15),OrderDate,103) OrderDate ,OrderNo ,OrderValue FROM tblHoOrder WHERE DeptId=CASE WHEN @vDeptId=0 THEN Id ELSE @vDeptId END
Hi All, Currently query is working fine but during high volume data it is taking hours and I need to optimize this query only (Means cannot park the code in sql command) Example query : //joining Product and Tax DataTable var JoinResult = (from p in dt.AsEnumerable() join t in dtTax.AsEnumerable() on p.Field<int>("Tax Id") equals t.Field<int>("Tax Id") select new { ProductName = p.Field<string>("Product Name"), BrandName = p.Field<string>("Brand Name"), ProductCategory = t.Field<string>("Product Category"), TaxCharge = t.Field<int>("Charge") }).ToList(); Regards Shehzad
This blog describes the usage of FROM and IN keyword in LINQ.
In this blog, we will learn about how we can remove the duplication from the string using HashSet
help me to convert this query to linq Select Count (d.eanumber) as Eas, dem. Model, month (dem. IncorporatedDate) as months, Year (dem. IncorporatedDate) as years from DeviationEngineModels dem join Deviation d on d.Id = dem. DeviationId where dem. IncorporatedDate is not null and dem. Published =1 and Year (dem. IncorporatedDate) = 2022 and d.IsDeleted !=1 group by month (dem. IncorporatedDate), dem. Model, Year (dem. IncorporatedDate) ORDER BY months
Hi In below LINQ, I wanted to filter the rows which has days value more than 90. But some row might have NULL value in days field. I wanted to handle those row which has NULL in days field and log the corresponding row details like name, class ,birthday and skip that row and continue with next row. ( Similar to Continue statement in for each loop) Could you help to get a solution? var tempItems = (from tmp in dt.AsEnumerable() where tmp .Field<int>("days") > 90 select new { Name= tmp["Name"], class = tmp["class"], birthdate = tmp["birthdate"], days= tmp["days"], amount = tmp["amount"], &nbs
I need to compare the same "PhoneNumber" attributes having the same "ID" for each element <List> <Connect ID="ID1" PhoneNumber="453585644878"> </Connect> <Connect ID="ID1" PhoneNumber="453585644878"> </Connect> <Connect ID="ID2" PhoneNumber="45655556658"> </Connect> <Connect ID="ID2" PhoneNumber="96685688787"> </Connect> <Connect ID="ID3" PhoneNumber="5766855577"> </Connect> <Connect ID="ID3" PhoneNumber="8565657787"> </Connect> <Connect ID="ID3" PhoneNumber="4565775235"> </Connect> <Connect ID="ID4" PhoneNumber="44545454545"> </Connect> </List> for example in , the first two connect equivalent phone numbers and in the other non-equivalent numbers.
Dear all I have a table with the following columns , Now I have two three rows with Department Employee Table Emp_ID First_Name Last_Name 1 NEW OLD 2 FOG HOP Employee Detail table Table_ID Emp_ID Department Salary Visit_Date 1 1 HR 1200 5/5/2021 2 2 HR 1300 8-8-2022 3 3 ICT 1400 01-01-2022 Now I want to get the employee detail with name Department,salary,Visit_Date I want to get only HR department employee and from HR only one Row whose date is latest date like 8-8-2022 below is my current query. var MyQuery=(from nn in db.EmployeeDetail from vv in db.Employee where vv.Emp_ID=nn.Emp_ID order by vv.department select new EmployeeDetail { visit_date=nn.Visit_Date, Salary=nn.Salary).FirstOrDefault(), }).ToList(); but it return two rows of HR i need one row with latest visit Date. }
The differences between IEnumerable and IQueryable.
LINQ is a program that was introduced as part of the .NET framework version 3.5 in 2007. LINQ allows developers to write efficient C# code using arrow functions to query collections of objects or from databases using libraries like Entity Framework.
Hi, I am in new in LINQ query so my question is can we use AsNoTracking in insert statement?if yes give me the example.
Hello community. I'm doing an insert form, and i'm trying to use a LastOrDefault to get the new value, and creating a new one binding it +1 , but i don´t know how to trasnlate this programatically. Could you help me? //LastOrDefaultpublic ListagemTimesheet CreateNewID(int ID){using (GestaoProjectosEntities lt = new GestaoProjectosEntities()){return lt.ListagemTimesheets.LastOrDefault(a => a.ID == ID);}}//form.CSint idtimesheet = int.Parse(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["ID"].ToString()); //find for an existing ID ListagemTimesheet timesheet = listagembll.CreateNewID(idtimesheet); //LastOrDefault //Create a new ID ?
select P.Id,p.Name,pp.Weightage from Person p inner join (Select * from ( SELECT * FROM [SL_Project_Management].[dbo].[PersonWiseActionHistory] where Id in ( select MAX(Id) from [SL_Project_Management].[dbo].[PersonWiseActionHistory] group by PersonId) )ss where convert(nvarchar(10),EffectFrom,103)=convert(nvarchar(10),'24/06/2022',103) and ActionTypeId=1)pp on p.Id=pp.PersonId
In this article, I will demonstrate how to use IEnumerable and IQueryable in C#. Also learn the differences between IEnumerable and IQueryable.
In this article we will see about LINQ Aggregate function with an example.
I am trying to convert a few CASE statements in a SQL query to LINQ and in need of assistance in doing so. Here is part of the SQL statement with the CASE statements: SELECT dt.DisplayText, CASE WHEN fsh.FieldName = 'SiteId' THEN 'SiteName' ELSE fsh.FieldName END as FieldName, fsh.FieldName, fsh.[Action], CASE WHEN fsh.FieldName = 'SiteId' THEN so.SiteName ELSE fsh.OldValue END as OldValue, CASE WHEN fsh.FieldName = 'SiteId' THEN sn.SiteName ELSE fsh.NewValue END as NewValue, fsh.OldValue, fsh.NewValue, u.UserName, fsh.ModifiedDate, fs.ProgramGroupYear, fs.CustomerId Part of LINQ with the CASE statements. I put the CASE statements in here as placeholders. Obviously those statements in LINQ won't work. public async Task<IEnumerable<HistoryRecord>> GetHistoryRecords(int documentTypeId, int programGroupYear, int customerId, DateTime? from, DateTime? to, CancellationToken cancellationToken) { Guard.Zero(documentTypeId, nameof(documentTypeId)); var query = _context.FileStoreHistories .Join(_context.FileStores, fsh => fsh.FileStoreId, fs => fs.FileStoreId, (fsh, fs) => new { fs.CustomerId, fs.ProgramGroupYear, fs.DisplayText, **CASE WHEN fsh.FieldName = 'SiteId' THEN 'SiteName' ELSE fsh.FieldName END as FieldName,** fsh.FieldName, fsh.Action, *****CASE WHEN fsh.FieldName = 'SiteId' THEN so.SiteName ELSE fsh.OldValue END as OldValue, CASE WHEN fsh.FieldName =
The image is saved in DB using particular ID. Now I need to display the image when that ID is selected. This has to be done in Angular using LINQ . Any examples for this case?
There is A situation where i have currently used Foreach inside the linq db.retailer_comm.Where(w => w.optcode == aa.optcode && remlist.Contains(w.userid)).ToList().ForEach(i => i.comm =aa.comm); The Above Statement is Working Fine, But I want to add two more operation inside the Foreach, like this db.retailer_comm.Where(w => w.optcode == aa.optcode && remlist.Contains(w.userid)).ToList().ForEach(i => i.comm =aa.comm , i.comm1=aa.comm1); But It's Give me Error, So How Can i Solve This Problem
Hi, I am getting this error in Entity Framework inner join. How can I resolve this error. without touching the database. I get error Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CS_AS" and "Turkish_CI_AS" in the equal to operation. I need to add below code. var result = from cartItem in contex.CartItem join article in contex.Article on cartItem.Articel_Oid equals article.Articel_Oid join saleSeason in contex.B2B_SaleSeasonDefinition on new { SaleSeasonOid = cartItem.SaleSeason_Oid, SaleSeasonId = cartItem.SaleSeason_Id } equals new { SaleSeasonOid = saleSeason.Oid, SaleSeasonId = saleSeason.Id } join customer in contex.CurrentCustomer on cartItem.Customer_Code equals customer.Code where cartItem.Customer_Code == Customer group cartItem by new { article.Articel_Oid, article.Articel_Code, article.Model_ArticelName, cartItem.SaleSeason_Oid, cartItem.SaleSeason_Id, cartItem.UnitPrice, customer.ShippingCost, customer.FreightVAT, cartItem.SubUnitPrice } into cart select new ArticleInCart { Articel_Oid = cart.Key.Articel_Oid, Article_Code = cart.Key.Articel_Code, Articel_Name = cart.Key.Model_ArticelName, SumQuantity = cart.Sum(x => x.Quantity), UnitPrice = cart.Key.UnitPrice,//cart.Sum(x => x.Price) / cart.Sum(x => x.Quantity), Price = cart.Sum(x => x.SubTotal), SaleSeason = cart
Need to display dates in descending order from database table. How to write LINQ query in C# to display dates in descending order? Eg: 21-03-2022 03-02-2022 17-04-2022 08-01-2022 31-01-2022 01-12-2021
In this blog, you will learn the difference between Single, SingleOrDefault, First, FirstOrDefault.