How adding items to list - c#

I have model in my project. Here is code of model
public partial class Logging
{
public string Imei { get; set; }
public DateTime CurDateTime { get; set; }
public Nullable<System.DateTime> GPSDateTime2 { get; set; }
public Nullable<decimal> Latitude2 { get; set; }
public Nullable<decimal> Longitude2 { get; set; }
public string Speed { get; set; }
public Nullable<int> Datatype { get; set; }
public int Id { get; set; }
[NotMapped]
public TimeSpan? FirstStartDifference
{
get
{
if (CurDateTime != null)
{
var midnight = new DateTime(CurDateTime.Year, CurDateTime.Month, CurDateTime.Day, 00, 00, 00);
var difference = CurDateTime - midnight;
return difference;
}
return null;
}
}
[NotMapped]
public TimeSpan? LastStartDifference
{
get
{
if (CurDateTime != null)
{
var midnight = new DateTime(CurDateTime.Year, CurDateTime.Month, CurDateTime.Day, 23, 59, 00);
var difference = midnight - CurDateTime;
return difference;
}
return null;
}
}
[NotMapped]
public int coeff = 2;
}
I need to get some items from database , it's first entry, where Datatype==1 and Last where Datatype ==2.
So I write this method on back-end
public JsonResult GetStops()
{
using (var ctx = new GoogleMapTutorialEntities())
{
var firstitem = ctx.Loggings.Where(x => x.Datatype == 2).AsEnumerable().Select(
x => new
{
lng = x.Longitude2,
lat = x.Latitude2,
difference = (int)(x.FirstStartDifference?.TotalMinutes ?? -1) * x.coeff
}).FirstOrDefault();
var lastItem = ctx.Loggings.Where(x => x.Datatype == 2).AsEnumerable().Select(
x => new
{
lng = x.Longitude2,
lat = x.Latitude2,
difference = (int)(x.LastStartDifference?.TotalMinutes ?? -1) * x.coeff
}).LastOrDefault();
List<Logging> items = new List<Logging> {firstitem, lastItem};
return Json(firstitem, JsonRequestBehavior.AllowGet);
}
}
After this I need to add firstitem and lastitem to list.
I write it like this List<Logging> items = new List<Logging> {firstitem, lastItem};
But I get an error
Severity Code Description Project File Line Suppression State
Error CS1950 The best overloaded Add method 'List.Add(Logging)' for the collection initializer has some invalid arguments Heatmap C:\Users\nemes\source\repos\Heatmap\Heatmap\Controllers\HomeController.cs 37 Active
Severity Code Description Project File Line Suppression State
Error CS1503 Argument 1: cannot convert from '' to 'Heatmap.Models.Logging' Heatmap C:\Users\nemes\source\repos\Heatmap\Heatmap\Controllers\HomeController.cs 37 Active
for this List<Logging> items = new List<Logging> {firstitem, lastItem};
How I can add them to List?

You are returning an anonymous type instead of Logging. The firstitem and lastItem are Anonymous Types. Change your code to this:
x => new Logging
{
Longitude2 = x.Longitude2,
Latitude2 = x.Latitude2,
//And other properties
}
And if you still get error probably it is because you cannot project onto a mapped entity then you need to create a DTO class with needed properties from the Logging entity:
public class LoggingDTO
{
public string Longitude2 { get; set; }
public string Latitude2 { get; set; }
//And other properties
}
Then:
x => new LoggingDTO

Related

How to use lambda expression to access correct data type?

I am using lambda expression to access values with data type, but the problem I have data type for Time as Time(7) on my local database and using Entity Framework. On my model this data type is define as DateTime.
How do I now access this data type to be time?
This is my code:
public List GetIncident_Details()
{
Entities incident = new Entities();
List result = new List();
var c_incident = incident.Incident_Template.Select(c => c).ToList();
if (c_incident != null && c_incident.Count() > 0)
{
foreach (var cData in c_incident)
{
Incident_DropDown model = new Incident_DropDown();
model.Title = cData.Title;
model.Description = cData.Description;
model.Date_Occurred = cData.Date_Occurred;
// How do I change this to have access?
// It's complaining about the data type object being set to a string?
model.Time = cData.Time;
model.Assignment_Group = cData.Assignment_Group;
model.Reported_CI = cData.Reported_CI;
result.Add(model);
}
}
return result;
}
public class Incident_DropDown
{
public string Title { get; set; }
public string Description { get; set; }
public string Date_Occurred { get; set; }
public DateTime Time { get; set; } // Time
public string Assignment_Group { get; set; }
public string Reported_CI { get; set; }
}
Took some advice from #alexey-rumyantsev, then had to test my code by interrogating model data type for Time it was Date Time, then change to Timespan. While testing this data type compare to my local database record and it was passing correct vales when debugging.
// Model name
public class Incident_DropDown
{
public string Title { get; set; }
public string Description { get; set; }
public string Date_Occured { get; set; }
public TimeSpan Time { get; set; } // had to change to work
public string Assignment_Group { get; set; }
public string Reported_CI { get; set; }
}
// Controller
public List<Incident_DropDown> GetIncident_Details()
{
Entities incident = new Entities();
List<Incident_DropDown> result = new List<Incident_DropDown>();
var c_incident = incident.Incident_Template.Select(c => c).ToList();
if (c_incident != null && c_incident.Count() > 0)
{
foreach (var cData in c_incident)
{
Incident_DropDown model = new Incident_DropDown();
model.Title = cData.Title;
model.Description = cData.Description;
model.Date_Occured = cData.Date_Occured;
model.Time = cData.Time; // This here enable to pass correct time as per database record
model.Assignment_Group = cData.Assignment_Group;
model.Reported_CI = cData.Reported_CI;
result.Add(model);
}
}
return result;
}

Resampling with Deedle duplicate keys

My code below resamples 5-minute interval to 1-day interval for the daily profit stats. The problem is that BacktestResult consists of duplicate CloseDate values, because I'm testing with multiple pairs (TRXUSDT, ETHUSDT and BTCUSDT). dailyProfit returns Series<DateTime, double>, which explains the exception. How can I make it grouped by Pair or something? It works fine when tested with one pair.
// Create series
var series = _backtestResults.ToOrdinalSeries();
// daily_profit = results.resample('1d', on = 'close_date')['profit_percent'].sum()
var dailyProfit = series.ResampleEquivalence(
index => new DateTime(series[index].CloseDate.Year, series[index].CloseDate.Month, series[index].CloseDate.Day, 0, 0, 0, DateTimeKind.Utc),
group => group.SelectValues(g => g.ProfitPercentage).Sum()).DropMissing();
// classes
public class BacktestResult
{
public string Pair { get; set; }
public decimal ProfitPercentage { get; set; }
public decimal ProfitAbs { get; set; }
public decimal OpenRate { get; set; }
public decimal CloseRate { get; set; }
public DateTime OpenDate { get; set; }
public DateTime CloseDate { get; set; }
public decimal OpenFee { get; set; }
public decimal CloseFee { get; set; }
public decimal Amount { get; set; }
public decimal TradeDuration { get; set; }
public SellType SellReason { get; set; }
}
Edit:
Example which takes the JSON data from pastebin:
using Deedle;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
namespace Resample
{
class Program
{
public class BacktestResultTest
{
public string Pair { get; set; }
public decimal ProfitPercentage { get; set; }
public decimal ProfitAbs { get; set; }
public decimal OpenRate { get; set; }
public decimal CloseRate { get; set; }
public DateTime OpenDate { get; set; }
public DateTime CloseDate { get; set; }
public decimal OpenFee { get; set; }
public decimal CloseFee { get; set; }
public decimal Amount { get; set; }
public decimal TradeDuration { get; set; }
public bool OpenAtEnd { get; set; }
public int SellReason { get; set; }
}
static void Main(string[] args)
{
// Take JSON data from pastebin
using var webClient = new WebClient();
var json = webClient.DownloadString("https://pastebin.com/raw/Dhp9202f");
// Deserialize the data
var data = JsonConvert.DeserializeObject<List<BacktestResultTest>>(json);
var ts = data.ToOrdinalSeries();
var byDateAndPair = ts.SelectKeys(kvp => Tuple.Create(kvp.Value.Value.CloseDate, kvp.Value.Value.Pair)).SortByKey();
// daily_profit = results.resample('1d', on = 'close_date')['profit_percent'].sum()
var dailyProfit2 = byDateAndPair.ResampleEquivalence(
k => Tuple.Create(new DateTime(k.Item1.Year, k.Item1.Month, k.Item1.Day), k.Item2),
g => g.Select(kvp => kvp.Value.ProfitPercentage).Sum());
// backtest_worst_day = min(daily_profit)
var worstDay2 = dailyProfit2.Min();
// backtest_best_day = max(daily_profit)
var bestDay2 = dailyProfit2.Max();
// winning_days = sum(daily_profit > 0)
var winningDays2 = dailyProfit2.SelectValues(x => x > 0).Sum();
// draw_days = sum(daily_profit == 0)
var drawDays2 = dailyProfit2.SelectValues(x => x == 0).Sum();
// losing_days = sum(daily_profit < 0)
var losingDays2 = dailyProfit2.SelectValues(x => x < 0).Sum();
Console.ReadLine();
}
}
}
You can use a custom data type as a key in Deedle. If you want to be able to use resampling on the series, then this needs to support IComparable. You can either define your own type or use built-in Tuple.
Assuming we have some very basic data:
var ts =
new[] {
KeyValue.Create(new DateTime(2020,1,1), new { Value = 1.0, Kind = "A" }),
KeyValue.Create(new DateTime(2020,1,2), new { Value = 1.0, Kind = "A" }),
KeyValue.Create(new DateTime(2020,1,3), new { Value = 1.0, Kind = "B" }),
KeyValue.Create(new DateTime(2020,1,4), new { Value = 1.0, Kind = "B" }),
}.ToSeries();
The first thing we need to do is to change the key to be the date together with a kind. (In fact, you can get into trouble earlier in your code if you had duplicate dates!)
var byDateAndKind =
ts.SelectKeys(kvp => Tuple.Create(kvp.Key, kvp.Value.Value.Kind)).SortByKey();
Now the key is Tuple<DateTime, string> consisting of the date and the kind. You can now use ResampleEquivalence on this. Here, we use year and kind as the new key and sum values in group:
var aggByYearAndKind =
byDateAndKind.ResampleEquivalence(
(k) => Tuple.Create(k.Item1.Year, k.Item2),
(g) => g.Select(kvp => kvp.Value.Value).Sum());
aggByYearAndKind.Print();
This will print a series that maps 2020, "A" to 2 and also 2020, "B" to 2.
EDIT You are right - this does not seem to work. I was able to get it to work using GroupBy instead of ResampleEquvialence:
var dailyProfit2 =
ts.GroupBy(kvp =>
new { Date = new DateTime(kvp.Value.CloseDate.Year, kvp.Value.CloseDate.Month, kvp.Value.CloseDate.Day), Kind = kvp.Value.Pair })
.SelectValues(g => g.Select(kvp => kvp.Value.ProfitPercentage).Values.Sum());
// backtest_worst_day = min(daily_profit)
var worstDay2 = dailyProfit2.Min();
// backtest_best_day = max(daily_profit)
var bestDay2 = dailyProfit2.Max();
// winning_days = sum(daily_profit > 0)
var winningDays2 = dailyProfit2.Where(x => x.Value > 0).Values.Sum();
// draw_days = sum(daily_profit == 0)
var drawDays2 = dailyProfit2.Where(x => x.Value == 0).Values.Sum();
// losing_days = sum(daily_profit < 0)
var losingDays2 = dailyProfit2.Where(x => x.Value < 0).Values.Sum();

Filter based on a string value in List<string> column in a table Entity Framework Core

I have a table with the following structure (code first approach using Entity Framework Core) in PostgreSQL
public class Product_Order
{
[Key]
public string product_number { get; set; }
public string customer_product_number { get; set; }
public List<string> product_statuses { get; set; }
public bool is_test { get; set; } = false;
public DateTime created_at { get; set; } = DateTime.UtcNow;
public DateTime updated_at { get; set; } = DateTime.UtcNow;
public string created_by { get; set; } = "system";
public string updated_by { get; set; } = "system";
}
Now, the product_statuses column usually contains of a list of statuses - ready, pickedup, scheduled, closed, cancelled.
I need to come up with a solution which returns me a list of product orders which DOES NOT CONTAIN orders which are closed or cancelled.
Here's the solution that I have at the moment which is not filtering as expected
_context.Product_Order.Where(t => t.is_test && !t.statuses.Contains("closed") && !t.statuses.Contains("cancelled")).ToList();
I think your code is ok for your data structure to find that information. I have created a dummy class and list to replicate your data and list. And I was able to find data by using you code. Sample Code given below what I have tested =>
void Test()
{
List<Product_Order> items = new List<Product_Order>();
var temp = new Product_Order() { product_number = "001", isTest = true };
temp.product_statuses = new List<string>();
temp.product_statuses.Add("good");
temp.product_statuses.Add("greate");
temp.product_statuses.Add("new");
items.Add(temp);
temp = new Product_Order() { product_number = "002", isTest = true };
temp.product_statuses = new List<string>();
temp.product_statuses.Add("good");
temp.product_statuses.Add("bad");
temp.product_statuses.Add("notnew");
items.Add(temp);
temp = new Product_Order() { product_number = "003", isTest = true };
temp.product_statuses = new List<string>();
temp.product_statuses.Add("n/a");
temp.product_statuses.Add("bad");
temp.product_statuses.Add("Closed");
items.Add(temp);
temp = new Product_Order() { product_number = "004", isTest = false };
temp.product_statuses = new List<string>();
temp.product_statuses.Add("n/a");
temp.product_statuses.Add("bad");
temp.product_statuses.Add("Cancelled");
items.Add(temp);
var finalOutput = items.Where(c => c.isTest == true && !c.product_statuses.Where(v => v.ToLower() == "closed").Any() && !c.product_statuses.Where(v => v.ToLower() == "cancelled").Any()).ToArray();
}
public class Product_Order
{
public string product_number { get; set; }
public bool isTest { get; set; }
public List<string> product_statuses { get; set; }
}
Finally , I think it is your data what not wright with you lambda expression. So, I modified for you a little bit.And that is
FINAL ANSWER:
var finalOutput = _context.Product_Order.Where(c => c.isTest == true && !c.product_statuses.Where(v => v.ToLower() == "closed").Any() && !c.product_statuses.Where(v => v.ToLower() == "cancelled").Any()).ToArray();
Please check my code and let me know.

Map one class data to another class with iteration

I have a C# project and looking for simple solution for map one class object data to list of another class object.
This is my input class
public class RatesInput
{
public string Type1 { get; set; }
public string Break1 { get; set; }
public string Basic1 { get; set; }
public string Rate1 { get; set; }
public string Type2 { get; set; }
public string Break2 { get; set; }
public string Basic2 { get; set; }
public string Rate2 { get; set; }
public string Type3 { get; set; }
public string Break3 { get; set; }
public string Basic3 { get; set; }
public string Rate3 { get; set; }
}
This is my another class structure
public class RateDetail
{
public string RateType { get; set; }
public decimal Break { get; set; }
public decimal Basic { get; set; }
public decimal Rate { get; set; }
}
it has a object like below. (For easiering the understanding, I use hardcoded values and actually values assign from a csv file)
RatesInput objInput = new RatesInput();
objInput.Type1 = "T";
objInput.Break1 = 100;
objInput.Basic1 = 50;
objInput.Rate1 = 0.08;
objInput.Type2 = "T";
objInput.Break2 = 200;
objInput.Basic2 = 50;
objInput.Rate2 = 0.07;
objInput.Type3 = "T";
objInput.Break3 = 500;
objInput.Basic3 = 50;
objInput.Rate3 = 0.06;
Then I need to assign values to "RateDetail" list object like below.
List<RateDetail> lstDetails = new List<RateDetail>();
//START Looping using foreach or any looping mechanism
RateDetail obj = new RateDetail();
obj.RateType = //first iteration this should be assigned objInput.Type1, 2nd iteration objInput.Type2 etc....
obj.Break = //first iteration this should be assigned objInput.Break1 , 2nd iteration objInput.Break2 etc....
obj.Basic = //first iteration this should be assigned objInput.Basic1 , 2nd iteration objInput.Basic2 etc....
obj.Rate = //first iteration this should be assigned objInput.Rate1, 2nd iteration objInput.Rate2 etc....
lstDetails.Add(obj); //Add obj to the list
//END looping
Is there any way to convert "RatesInput" class data to "RateDetail" class like above method in C#? If yes, how to iterate data set?
Try this:
public class RatesList : IEnumerable<RateDetail>
{
public RatesList(IEnumerable<RatesInput> ratesInputList)
{
RatesInputList = ratesInputList;
}
private readonly IEnumerable<RatesInput> RatesInputList;
public IEnumerator<RateDetail> GetEnumerator()
{
foreach (var ratesInput in RatesInputList)
{
yield return new RateDetail
{
RateType = ratesInput.Type1,
Break = Convert.ToDecimal(ratesInput.Break1, new CultureInfo("en-US")),
Basic = Convert.ToDecimal(ratesInput.Basic1, new CultureInfo("en-US")),
Rate = Convert.ToDecimal(ratesInput.Rate1, new CultureInfo("en-US"))
};
yield return new RateDetail
{
RateType = ratesInput.Type2,
Break = Convert.ToDecimal(ratesInput.Break2),
Basic = Convert.ToDecimal(ratesInput.Basic2),
Rate = Convert.ToDecimal(ratesInput.Rate2, new CultureInfo("en-US"))
};
yield return new RateDetail
{
RateType = ratesInput.Type3,
Break = Convert.ToDecimal(ratesInput.Break3),
Basic = Convert.ToDecimal(ratesInput.Basic3),
Rate = Convert.ToDecimal(ratesInput.Rate3, new CultureInfo("en-US"))
};
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
And use:
var list = new RatesList(new List<RatesInput>() { objInput });
foreach (var item in list)
{
Console.WriteLine(item.Basic);
}
You can use Reflection to get the properties info like this:
var props = objInput.GetType().GetProperties();
var types = props.Where(x => x.Name.StartsWith("Type"))
.Select(x => x.GetValue(objInput)).ToList();
var breaks = props.Where(x => x.Name.StartsWith("Break"))
.Select(x => x.GetValue(objInput)).ToList();
var basics = props.Where(x => x.Name.StartsWith("Basic"))
.Select(x => x.GetValue(objInput)).ToList();
var rates = props.Where(x => x.Name.StartsWith("Rate"))
.Select(x => x.GetValue(objInput)).ToList();
List<RateDetail> lstDetails = new List<RateDetail>();
for (int i = 0; i < types.Count; i++)
{
lstDetails.Add(new RateDetail
{
RateType = types[i].ToString(),
Break = Convert.ToDecimal(breaks[i]),
Basic = Convert.ToDecimal(basics[i]),
Rate = Convert.ToDecimal(rates[i])
});
}

Assign value to new List property (ASP.NET MVC)

I have table class Logging
Here is code:
public partial class Logging
{
public string Imei { get; set; }
public DateTime CurDateTime { get; set; }
public Nullable<System.DateTime> GPSDateTime2 { get; set; }
public Nullable<decimal> Latitude2 { get; set; }
public Nullable<decimal> Longitude2 { get; set; }
public int Speed { get; set; }
public Nullable<int> Datatype { get; set; }
public int Id { get; set; }
}
Also I have ViewModel
public class HeatmapViewModel
{
public decimal? Latitude2 { get; set; }
public decimal? Longitude2 { get; set; }
public int FirstStartDifference { get; set; }
public int LastStartDifference { get; set; }
public int coeff = 2;
public int Difference;
}
I have method in repository where I do all calculations
Here is code
var allitems = ctx.Loggings.AsEnumerable().Select(
x => new Logging
{
Longitude2 = x.Longitude2,
Latitude2 = x.Latitude2,
CurDateTime = x.CurDateTime,
Datatype = x.Datatype
});
var filteredQuery = allitems.Where(x => x.Datatype == 1 || x.Datatype == 2).OrderByDescending(x => x.Id).ToList();
for (int i = 1; i < filteredQuery.Count; i++)
{
if (filteredQuery[i].Datatype == 2 && filteredQuery[i - 1].Datatype == 1)
{
TimeSpan differenceTicks = filteredQuery[i].CurDateTime - filteredQuery[i - 1].CurDateTime;
var differenceInMinutes = (int) differenceTicks.TotalMinutes;
}
}
items.Add(new HeatmapViewModel
{
Latitude2 = allitems.Longitude2,
Longitude2 = allitems.Longitude2,
Difference = differenceInMinutes
});
I have trouble with this block of code:
items.Add(new HeatmapViewModel
{
Latitude2 = allitems.Longitude2,
Longitude2 = allitems.Longitude2,
Difference = differenceInMinutes
});
Here is errors:
Severity Code Description Project File Line Suppression State
Error CS1061 'IEnumerable' does not contain a definition for 'Longitude2' and no extension method 'Longitude2' accepting a first argument of type 'IEnumerable' could be found (are you missing a using directive or an assembly reference?) Heatmap C:\Users\nemes\source\repos\Heatmap\Heatmap\Repository\HeatmapRepository.cs 91 Active
Severity Code Description Project File Line Suppression State
Error CS1061 'IEnumerable' does not contain a definition for 'Longitude2' and no extension method 'Longitude2' accepting a first argument of type 'IEnumerable' could be found (are you missing a using directive or an assembly reference?) Heatmap C:\Users\nemes\source\repos\Heatmap\Heatmap\Repository\HeatmapRepository.cs 92 Active
Severity Code Description Project File Line Suppression State
Error CS0103 The name 'differenceInMinutes' does not exist in the current context Heatmap C:\Users\nemes\source\repos\Heatmap\Heatmap\Repository\HeatmapRepository.cs 93 Active
How I can solve them?
Your problem is: allitems is an IEnumerable, so you can't use allitems.Longitude2 to get value of Longitude2. It's not a single item.
I think you should put items.Add(...) block to for loop.
And use filteredQuery[i].Longitude2 instead of allitems.Longitude2.
Like this
var filteredQuery = (
from log in ctx.Loggings
where log.Datatype == 1 || log.Datatype == 2
orderby log.Id descending
select log
).ToList();
var items = new List<HeatmapViewModel>();
for (int i = 1; i < filteredQuery.Count; i++)
{
if (filteredQuery[i].Datatype == 2 && filteredQuery[i - 1].Datatype == 1)
{
TimeSpan differenceTicks = filteredQuery[i].CurDateTime - filteredQuery[i - 1].CurDateTime;
items.Add(new HeatmapViewModel
{
Latitude2 = filteredQuery[i].Longitude2,
Longitude2 = filteredQuery[i].Longitude2,
Difference = (int)differenceTicks.TotalMinutes
});
}
}

Categories

Resources