This is my code:
DateTime epoch = new DateTime(1970, 1, 1);
var result = (from row in InBoundtable.AsEnumerable()
group row by row.Field <string> ("Date") into grp
select new {
AbandonCalls = grp.Sum((r) => Double.Parse(r["AvgAbandonedCalls"].ToString())),
Date = ((DateTime.Parse(grp.Key)) - epoch).TotalMilliseconds
}).ToList();
where InBoundtable is a datatable.
now I have a string array campains
my question is there a way so in the select statement above I can make where the campain field, which is a string field, is either one of the values in the campains array?
You can use Enumerable.Contains("campain value"):
var query = from row in InBoundtable.AsEnumerable()
where campains.Contains(row.Field<string>("Campain"))
group row by row.Field <string> ("Date") into grp
select new {
AbandonCalls = grp.Sum(r => Double.Parse(r["AvgAbandonedCalls"].ToString())),
Date = ((DateTime.Parse(grp.Key)) - epoch).TotalMilliseconds
};
var result = query.ToList();
Related
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();
Actually I want to return the data from different lists based on Date. When i'm using this i'm getting data upto #Var result but i'm unnable to return the data. The issue with this is i'm getting error #return result. I want to return the data #return result. I'm using Linq C#. Can anyone help me out?
public List<CustomerWiseMonthlySalesReportDetails> GetAllCustomerWiseMonthlySalesReportCustomer()
{
var cbsalesreeport = (from cb in db.cashbilldescriptions
join c in db.cashbills on cb.CashbillId equals c.CashbillId
join p in db.products on cb.ProductId equals p.ProductId
select new
{
Productamount = cb.Productamount,
ProductName = p.ProductDescription,
CashbillDate = c.Date
}).AsEnumerable().Select(x => new ASZ.AmoghGases.Model.CustomerWiseMonthlySalesReportDetails
{
Productdescription = x.ProductName,
Alldates = x.CashbillDate,
TotalAmount = x.Productamount
}).ToList();
var invsalesreeport = (from inv in db.invoices
join invd in db.invoicedeliverychallans on inv.InvoiceId equals invd.InvoiceId
select new
{
Productamount = invd.Total,
ProductName = invd.Productdescription,
InvoiceDate = inv.Date
}).AsEnumerable().Select(x => new ASZ.AmoghGases.Model.CustomerWiseMonthlySalesReportDetails
{
Productdescription = x.ProductName,
Alldates = x.InvoiceDate,
TotalAmount = x.Productamount
}).ToList();
var abc = cbsalesreeport.Union(invsalesreeport).ToList();
var result = (from i in abc
group i by new { Date = i.Alldates.ToString("MMM"), Product = i.Productdescription } into grp
select new { Month = grp.Key, Total = grp.Sum(i => i.TotalAmount) });
**return result;**
}
You can either convert your result to a List before returning it using return result.ToList() or make your method return an IEnumerable<CustomerWiseMonthlySalesReportDetails> instead of List.
As your result is an enumeration of anonymous types you have to convert them to your CustomerWiseMonthlySalesReportDetails-type first:
select new CustomerWiseMonthlySalesReportDetails{ Month = grp.Key, Total = grp.Sum(i => i.TotalAmount) });
Assuming your type has exactly the members returned by the select.
EDIT: So your code should look like this:
var result = (from i in abc
group i by new { Date = i.Alldates.ToString("MMM"), Product = i.Productdescription } into grp
select new CustomerWiseMonthlySalesReportDetails{ Month = grp.Key, Total = grp.Sum(i => i.TotalAmount) });
return result.ToList();
You can assume Alldates property if is date of one of groups that month of date is in right place:
var result = (from i in abc
group i by new { Date = i.Alldates.ToString("MMM"), Product = i.Productdescription }
into grp
select new CustomerWiseMonthlySalesReportDetails{
Productdescription = grp.Key.Product,
TotalAmount = grp.Sum(i => i.TotalAmount),
Alldates =grp.First(i=>i.Alldates ) })
.ToList();
This is my old code
DateTime epoch = new DateTime(1970, 1, 1);
var result = (from row in InBoundtable.AsEnumerable()
group row by row.Field<string>("Date") into grp
select new
{
AbandonCalls = grp.Sum((r) => Double.Parse(r["AvgAbandonedCalls"].ToString())),
Date = ((DateTime.Parse(grp.Key.ToString())) - epoch).TotalMilliseconds
}).ToList();
as you see, I am making group on Date column.
Can I make the group on Date and Slice columns? where both of them is string value
Create an anonymous type using those two columns. Both columns will be part of the group's "key", so you'll have to access them separately.
DateTime epoch = new DateTime(1970, 1, 1);
var result = (from row in new DataTable().AsEnumerable()
group row by new
{
Date = row.Field<string>("Date"),
Slice = row.Field<string>("Slice")
}
into grp
select new
{
AbandonCalls = grp.Sum((r) => Double.Parse(r["AvgAbandonedCalls"].ToString())),
Date = ((DateTime.Parse(grp.Key.Date)) - epoch).TotalMilliseconds,
grp.Key.Slice
}).ToList();
I have the following query which works fine:
var bands = new List<TimeBand>()
{
new TimeBand(){Region = 10,PeriodId = 5,StartDate = new DateTime(2013, 04, 01),EndDate = new DateTime(2014, 05, 31),DayName = "Friday",StartTime = "00:00",EndTime = "07:00"},
new TimeBand(){Region = 10,PeriodId = 5,StartDate = new DateTime(2013, 04, 01),EndDate = new DateTime(2013, 05, 31),DayName = "Friday",StartTime = "07:00",EndTime = "00:00"},
new TimeBand(){Region = 10,PeriodId = 4,StartDate = new DateTime(2013, 06, 01),EndDate = new DateTime(2013, 08, 31),DayName = "Saturday",StartTime = "20:00",EndTime = "00:00"}
};
var query = (from x in bands
group x by new {x.Region, x.DayName}
into grp
select new TimeBand()
{
Region = grp.Key.Region,
DayName = grp.Key.DayName,
StartDate = grp.Min(x => x.StartDate),
EndDate = grp.Max(x => x.EndDate)
}).ToList();
But as I group the results by Region and Dayname I am not getting the other columns in my result i.e StartTime and EndTime.
If this was a SQL query I would have used this grouped results in a subquery and get the other columns as well.
Is there any way of modifying this so I also get the properties which are not included in the group by statement.
Thanks
After grouping source items you have sequence of groups. How you will project these groups is up to you. Usually you select grouping keys and some aggregated values on each group (that is how SQL works). But you can select each group itself, or first item from each group, or some value from last group item:
from b in bands
group b by new { b.Region, b.DayName } into g
select new {
g.Key.Region,
g.Key.DayName,
StartDate = g.Min(x => x.StartDate),
EndDate = g.Max(x => x.EndDate),
AllBandsFromGroup = g,
FirstBand = g.First(),
LastBandPeriod = g.Last().Period
}
Just select out the whole group if you want the keys as well as all of the values for all of the items in the groups:
select grp;
The other option is to select out a sequence of all values of the columns that you want from a group:
select new TimeBand()
{
Region = grp.Key.Region,
DayName = grp.Key.DayName,
StartDates = grp.Select(x => x.StartDate),
EndDates = grp.Select(x => x.EndDate)
}
You'd only need to do this if you didn't want to pull down the data for some number of other columns. If you want all of the columns, just use the first option.
var query = (from x in bands
group x by new { x.Region, x.DayName }
into grp
select new
{
Region = grp.Key.Region,
DayName = grp.Key.DayName,
MinStartDate = grp.Min(x => x.StartDate),
AllStartDates = grp.Select(k => k.StartDate).ToList(),
EndDate = grp.Max(x => x.EndDate),
AllEndDates = grp.Select(k => k.EndDate).ToList(),
}).ToList();
It seems your are trying to find the minimum start date and time and maximum end date and time for each group. This might be much easier if you combine date and time into a single property.
Otherwise you will need a IComparer<TimeBand> for start date and time and another one for end date and time.
If you don't want to combine date and time you can write methods to get the combined values:
public DateTime GetStart()
{
int hour = int.Parse(StartTime.Substring(0, 2));
int minute = int.Parse(StartTime.Substring(3, 2));
return new DateTime(StartDate.Year, StartDate.Month, StartDate.Day, hour, minute, 0);
}
public DateTime GetEnd()
{
int hour = int.Parse(EndTime.Substring(0, 2));
int minute = int.Parse(EndTime.Substring(3, 2));
return new DateTime(EndDate.Year, EndDate.Month, EndDate.Day, hour, minute, 0);
}
Now you can group the bands and for each group find the minimum start and maximum end:
var query = from x in bands
group x by new
{
x.Region,
x.DayName
}
into grp
select new TimeBand()
{
Region = grp.Key.Region,
DayName = grp.Key.DayName,
StartDate = grp.Min(x => x.StartDate),
StartTime = grp.Min(x => x.GetStart()).ToShortTimeString(),
EndDate = grp.Max(x => x.EndDate),
EndTime = grp.Max(x => x.GetEnd()).ToShortTimeString(),
};
This is however not very elegant. I would prefer to combine date and time in the first place.
I have a list of dates. I would like to query the list and return a list of pairs where the first item is a date and the second is the date which occurs just before the first date (in the list).
I know this could easily be achieved by sorting the list and getting the respective dates by index, I am curious how this could be achieved in LINQ.
I've done this in SQL with the following query:
SELECT Date,
(SELECT MAX(Date)
FROM Table AS t2
WHERE t2.Date < t1.Date) AS PrevDate
FROM Table AS t1
It is easy as converting your current query into a LINQ query:
var result = table.Select(x =>
new
{
Date = x.Date,
PrevDate = table.Where(y => y.Date < x.Date)
.Select(y => y.Date)
.Max()
});
List<DateTime> dates = new List<DateTime>()
{
DateTime.Now.AddDays(1),
DateTime.Now.AddDays(7),
DateTime.Now.AddDays(3),
DateTime.Now.AddDays(6),
DateTime.Now.AddDays(5),
DateTime.Now.AddDays(2),
DateTime.Now.AddDays(3),
};
dates = dates.OrderByDescending(x => x).ToList();
var result = dates.Skip(1)
.Select((x, i) => new { Date = dates[i], PreviousDate = x });