i have table
id pagenane username
i want this sql query
select pagename, count(*) as num from pagestat where username='name' group by pagename
how can i do it by linq?
Well, try this:
var query = from row in context.pageStat
where row.UserName == "name"
group row by row.PageName into g
select new { PageName = g.Key, Count = g.Count() };
var retVal = (from s in dataContext.YourTable where
s.UserName.Equals("name")
group s by s.PageName into k
select new {PageName = k.Key, Count = k.Count() }).ToList();
Related
My SQL Server query (below) works perfectly fine, and I'm trying to convert it to LinQ in C#.
SQL Query:
SELECT addressline3, city, COUNT(*) as 'InstitutionNumber'
FROM institutionenquiries
WHERE CITY = 'AHMEDABAD'
GROUP BY addressline3, city
ORDER BY city;
Desired output is:
I'm able to draw the LinQ query in below format, which gives me correct output
(except for COUNT(*) as 'InstitutionNumber').
LINQ Query:
var obj = (from u in dbContext.InstitutionEnquiry
where u.City == data.Trim().ToLower()
select new {
AddressLine3 = u.AddressLine3.Trim().ToLower(),
City = u.City.Trim().ToLower(),
InstitutionNumber = (from a in dbContext.InstitutionEnquiry
where a.City == data.Trim().ToLower()
select a).Count()
}).ToList();
This gives me count for 'InstitutionNumber' = 3 for all.
I'm not able to get the count aspect correctly. I've referred to this post's answer and it gives me only count, but I'm not able to nest it within my LinQ query.
Any helpful inputs will be appreciated.
The first observation is that since SQL has a GROUP BY, LINQ should have a GroupBy, too.
The second observation is that since non-aggregate columns in SQL are group by columns, the results you select in LINQ would come from the group's key.
Now we can write the query:
var res = dbContext.InstitutionEnquiry
.Where(u => u.City == data.Trim().ToLower())
.GroupBy(u => new {
AddressLine3 = u.AddressLine3.Trim().ToLower(),
City = u.City.Trim().ToLower()
}).Select(g => new {
g.Key.AddressLine3,
g.Key.City,
Count = g.Count()
}).ToList();
I think you can use this LinQ :
var obj = dbContext.InstitutionEnquiry
// WHERE CITY = 'AHMEDABAD'
.Where(w => w.City == "AHMEDABAD") // => Note
// GROUP BY addressline3, city
.GroupBy(g => new {g.AddressLine3, g.City})
// SELECT addressline3, city, COUNT(*) as 'InstitutionNumber'
.Select(c => new {c.Key.AddressLine3, c.Key.City, InstitutionNumber = c.Count()})
// ORDER BY city
.OrderBy(o=> o.City)
.ToList();
Note: For ignoring case sensitivity You can use :
.Where(string.Equals(w.City.Trim(), data.Trim(), StringComparison.CurrentCultureIgnoreCase))
LINQ :
var obj = (from p in dbContext.InstitutionEnquiry
group p by new
{
p.addressline3,
p.city
} into grp
select new
{
grp.Key.addressline3,
grp.Key.city,
InstitutionNumber = grp.Count(),
}).ToList();
Equivalent Lambda expression :
var obj = dbContext.InstitutionEnquiry
.GroupBy(p => new { p.addressline3, p.city})
.Select(p => new { p.Key.addressline3, p.Key.city, InstitutionNumber = p.Count() })
.ToList();
I want to use that query in ef:
select count(number) as CountOfNumber ,number, name from table_1 group by number, name order by CountOfNumber desc
How can I use count on column and add this column new name.
You need to use GroupBy, OrderBy and Count combination:
var results = (from item in db.table_1
group item by new { item.name, item.number } into grouping
orderby grouping.Count() descending
select new
{
name = grouping.Key.name,
number = grouping.Key.number,
CountOfNumber = grouping.Count()
}).ToList();
https://msdn.microsoft.com/en-us/library/bb545971.aspx
You can use the Count method on the group. Where context is your Entity Framework data context or any IEnumerable.
var results = from t in context.table_1
group t by new { t.number, t.name } into g
orderby g.Count() descending
select new { number = g.Key.number, name = g.Key.name, count = g.Count() };
I have a table:
DataTable store_temp = new DataTable();
store_temp.Columns.Add("patn");
store_temp.Columns.Add("rf");
store_temp.Columns.Add("name");
store_temp.Columns.Add("conv");
store_temp.Columns.Add("conv_type");
store_temp.Columns.Add("recorddate");
store_temp.Columns.Add("executiondate");
My C# code :
int i = 0;
var rowsgroups = (from row in store_temp.AsEnumerable().GroupBy(row =>
row.Field<string>("patn"))
.OrderBy((g => g.OrderByDescending(y => y.Field<string("executiondate")).ThenByDescending(y =>
y.Field<string>("rf"))))
select new
{
patn = row.ElementAt(i),
rf_num = ++i,
}).ToArray();
I want the lambda experession, which is equivalent to:
select patn, rf,
> row_number() over( partition by patn order by executiondate,rf )
as rf_num,
name, conv,conv_type, recorddate, executiondate
from store_temp2
But, lambda syntax ... var rowsgroups has just a one row..
I want to show all rows in store_temp.
What should I do to fix the query?
row_number() over(partition by patn order by executiondate, rf)
means in LINQ you need to group by patn, then order each group by executiondate, rf, then use the indexed Select overload to get row numbering inside the group, and finally flatten the result with SelectMany.
With that being said, the equivalent LINQ query could be something like this:
var result = store_temp.AsEnumerable()
.GroupBy(e => e.Field<string>("patn"), (key, elements) => elements
.OrderBy(e => e.Field<string>("executiondate"))
.ThenBy(e => e.Field<string>("rf"))
.Select((e, i) => new
{
patn = key,
rf = e.Field<string>("rf"),
rf_num = i + 1,
name = e.Field<string>("name"),
conv = e.Field<string>("conv"),
conv_type = e.Field<string>("conv_type"),
recorddate = e.Field<string>("recorddate"),
executiondate = e.Field<string>("executiondate")
}))
.SelectMany(elements => elements)
.ToArray();
Try something like this
select new
{
rowNum = store_temp.Rows.IndexOf(row),
patn = row.ElementAt(i),
rf_num = ++i,
}).ToArray();
I don't think you required any groupby as per your required sql
var i=0;
var rowsgroups = (from row in store_temp.AsEnumerable()
orderby row.Field<string>("executiondate") descending,
row.Field<string>("rf") descending
select new
{
patn = row.Field<string>("patn"),
rf_num = ++i,
name = row.Field<string>("name"),
conv = row.Field<string>("conv"),
conv_type = row.Field<string>("conv_type"),
recorddate = row.Field<string>("recorddate"),
executiondate = row.Field<string>("executiondate")
}).ToArray();
I have some linq which returns a list of properties and the number of bookings for a given year. However if a property has no bookings then it is not included in the resultset.
var bookings = from b in db.Bookings
orderby b.PropertyId
where b.StartDate.Year == Year
group b by b.Property.Title into grp
select new { key = grp.Key, cnt = grp.Count() };
How can this be changed to include properties with no bookings?
I'm assuming there's a Properties table based on your code. You need to select from Properties instead:
var bookings = from p in db. Properties
orderby p.Id
group p by p.Title into grp
select new
{
key = grp.Key,
cnt = grp.Count(p => p.Bookings.Where(b => b.StartDate.Year == Year))
};
I guess you should filter on year in the count, then
var bookings = from b in db.Bookings
orderby b.PropertyId
group b by b.Property.Title into grp
select new {
key = grp.Key,
cnt = grp.Count(x => x.StartDate.Year == Year)
};
I've got a T-SQL query similar to this:
SELECT r_id, r_name, count(*)
FROM RoomBindings
GROUP BY r_id, r_name
I would like to do the same using LINQ. So far I got here:
var rooms = from roomBinding in DALManager.Context.RoomBindings
group roomBinding by roomBinding.R_ID into g
select new { ID = g.Key };
How can I extract the count(*) and r_name part?
Try this:
var rooms = from roomBinding in DALManager.Context.RoomBindings
group roomBinding by new
{
Id = roomBinding.R_ID,
Name = roomBinding.r_name
}
into g
select new
{
Id = g.Key.Id,
Name = g.Key.Name,
Count = g.Count()
};
Edit by Nick - Added method chain syntax for comparison
var rooms = roomBinding.GroupBy(g => new { Id = g.R_ID, Name = g.r_name })
.Select(g => new
{
Id = g.Key.Id,
Name = g.Key.Name,
Count = g.Count()
});