I want to fetch distinct date from a DataTable. Currently I'm using the below code:
MyDataTable.DefaultView.ToTable(true, "MyDateColumn");
This code considers the time too but I don't want the time to be considered. I wrote the below code to select only Date Part but while making the distinct it considers the time too.
MyDataTable.AsEnumerable()
.Select(row => new { MyDateColumn = row.Field<DateTime>("MyDateColumn").ToString("d") }).Distinct();
Please help me to select only distinct date(i.e by ignoring time).
You can try Selecting the column by just the Date property of the column:
MyDataTable.AsEnumerable()
.Select(row => row.Field<DateTime>("MyDateColumn").Date).Distinct();
Related
This is mysql query:
select
convert(date,convert(char(11),[Bill Date])) as date,
SUM(Amount) as total from Bills
group by [Bill Date]
order by date asc
What will be its LINQ to SQL with entitiy?
You can use LINQ GroupBy method with Sum method
You may use the DbFunctions.TruncateTime method on the BillDate datetime field to eliminate the timestamp part when grouping on the date (assuming you want to get total for each day)
var groupedSum= db.Bills.GroupBy(x => DbFunctions.TruncateTime(x.BillDate))
.Select(x => new
{
Total= x.Sum(g => g.Amount),
Date = x.Key
}).OrderBy(f=>f.Date).ToList();
This gives you a list of anonymous objects with a Day property and a Total property.
Assuming db is your db context object and Bills is a property of type DbSet<Bill>
DbFunctions.TruncateTime method is in System.Data.Entity namespace. So make sure you have a using statement to import that.
How do we select all the record of particular year (e.g. 2014) from a datatable where one of the column value(here 2014) is repeated on multiple rows of
table using linq or any other method in C#.
This is the datatable:
It's been a while since I've worked with DataTables but I think this should do it.
To select rows where the year is duplicated across more than one row:
dt.AsEnumerable().GroupBy(x => x["Year"]).Where(x => x.Count() > 1);
To select only the rows for a particular year:
dt.AsEnumerable().Where(x => x["Year"] == "2014");
Where dt is your System.Data.DataTable.
If you are trying to retrieve all the records lies on the Year 2014, use following linq query,IT will check your data column has data or not, I am sure it will works..
//selecting all the records of 2014
IEnumerable<DataRow> dtrow = default(IEnumerable<DataRow>);
dtrow = yourtable.AsEnumerable().Where(x => x.Field<Int64>("year") == Convert.ToInt64("2014"));
if (dtrow.Count() > 0)
{
dataTbl = dtrow.CopyToDataTable(); //dataTbl is the DataTable
}
Try to do it in database since it is faster than C#. DB can have index but C# does not have.
select *, count(1) as totalCount
group by year
having totalCount > 1
Is there any way to write a linq query to result in :
select Count(Id) from tbl1
because
tbl1.Select(q=>q.Id).Count()
doesn't translate to the result that I want
update :
it returns :
select count(*) from tbl1
Update after answer :
I tested the scenario with more than 21,000,000
Is there any way to write a linq query to result in.
No. First thing is to understad what you need, for sample, in T-SQL, you can use:
COUNT(*) will counts the rows in your table
COUNT(column) will counts the entries in a column - ignoring null values.
If you need to count how many rows you have, just use
var total = tbl1.Count();
If you need to see how many entities you have where a specific column is not null, then use a filter overloads of Count method.
var total = tbl1.Count(x => x.Id != null);
No, it is not possible. There is not difference realted with performance using Count(*) or ´Count(Id), even more if yourId` is the primary key.
I did an experiment with a table here with more than one million tuples. See the executioon plan of both queries. The first one is the select count(*) and second one is select count(id). The id is the primary key (sorry the results are in portuguese-brazil):
Using count(field) in sql counts all non-null values. In linq, you can say:
tbl1.Where(q => q.Id != null).Count();
or simply:
tbl1.Count(q => q.Id != null);
A possibility to get
select Count(Id) from tbl1
would be
tbl1.Where(q => q.Id != null).Select(x => x.Id).Distinct().Count();
The above Where is there to avoid null values. If you want them to also be counted, the Where needs to be eliminated and the Select adjusted to deal with null entries.
Additionally if you don't want to count just distinct values then the Select and Distinct parts can be disregarded.
I have a table:
Table { Id, Date, Number, Bool }
I need to group it by Number, select the row with max Date inside each group, and retrieve Id for each group. In the end I need to filter that to only have records that are !Bool. I am trying to do this with Linq Nhibernate.
This SQL seems to be doing what I want:
select Id from
(select MAX(Date) as Dt, Number as N from Table group by Number) t, Table table
where table.Date = t.Dt and table.Number = t.N and table.Bool = 0
but turns out NHibernate does not allow for subqueries to be in from. How do I write this with Linq Nhibernate?
It's also quite important for it to be efficient, so I would rather avoid having subqueries in select or where if they iterate over the whole set and (N+1) query problem.
The straightforward approach doesn't work either:
Session.Query<Table>().GroupBy(x => x.Number)
.Select(x => x.Where(y => y.Date == x.Max(z => z.Date)))...
I like to group a datatable by a known column but the rest of the columns are unknown. The first table in the picture is the source and the second table is the one i like to produce. Only the column that is needed to group by is sure to be there. I don't know the rest of the columns so it must be dynamic.
So far, i have tried using Linq but it doesn't product the output i wanted.
var dt = res.AsEnumerable()
.GroupBy(r => r.Field<string>("GroupBy"))
.SelectMany(t => t.ToList())
.CopyToDataTable();
When you talk about pivoting a table, you are usually summarizing the data in some fashion -- counting, totaling, averaging. If you only know one column, you can't really pivot it other than to count how many rows are in each group:
var dt = res
.AsEnumerable()
.GroupBy(r => r.Field<String>("ColumnToGroup"))
.Select(r => new { Key = r.Key, Count = r.Count() });
Gives you a pivot table that looks something like:
Key Count
London 2
Manchester 2
To do a useful pivot, you have to know something about the data in the table.