Linq query - varying datatype on column - c#

I'm running the query below :-
var Values = from data in DtSet.Tables["tblCosts"].AsEnumerable()
group data by new
{
InvNo = data.Field<double>("InvoiceNo"),
AccRef = data.Field<double>("SiteRefNum"),
}
into g
select new
{
Code = "1",
InvType = "I",
Account = g.Key.AccRef,
InvNo = g.Key.InvNo,
ChargeTotal = g.Sum(d => d.field<double>("Charge")
};
Due to the way the data is imported into the datatable (from Excel) sometimes the datatype of AccRef is double and sometimes it's string. Is there a way to overcome this at runtime, as I'd prefer to not have the user modify the source data in Excel before importing.

You can use Convert.ToDouble with objects, so it should work for double and for string:
var Values = from data in DtSet.Tables["tblCosts"].AsEnumerable()
group data by new
{
InvNo = data.Field<double>("InvoiceNo"),
AccRef = Convert.ToDouble(data["SiteRefNum"]),
}
into g
select new
{
Code = "1",
InvType = "I",
Account = g.Key.AccRef,
InvNo = g.Key.InvNo,
ChargeTotal = g.Sum(d => d.Field<double>("Charge"))
};
Of course that works only if SiteRefNum is actually convertable to a double.

Related

How to compare date in linq c#

i have 'created date' and 'closed date' in my file and i'm converting it in json so i have that dates in json.
in my method i have two parameter like from date and to date and i want to count particular column data of my file between from date and to date.so how can we write code to fetch it using linq.
i tried this...
public JsonResult StatusDerails(DateTime from,DateTime to)
{
string csvurl = WebConfigurationManager.AppSettings["csvfileurl"];
var lines = System.IO.File.ReadAllLines(csvurl).Skip(1);
List<Product> prdt = new List<Product>();
foreach (string line in lines)
{
Product c1 = new Product();
var split = line.Split(',');
c1.ID = Int32.Parse(split[0]);
c1.Area_Path = split[1];
c1.IterationPath = split[2];
c1.State = split[3];
c1.Reason = split[4];
c1.Priority = Int32.Parse(split[5]);
c1.Severity = split[6];
c1.Tags = split[7];
c1.Title = split[8];
c1.CreatedDate = split[9];
c1.CreatedBy = split[10];
c1.ResolvedDate = split[11];
c1.ResolvedBy = split[12];
c1.ClosedDate = split[13];
c1.AssignedTo = split[14];
prdt.Add(c1);
}
//var list = prdt.GroupBy(a=>a.AreaPath).Select(a=>new UIproduct() {
var productName = prdt.Select(a => a.Area_Path).Distinct();
List<StatusDetail> statusdetail = new List<StatusDetail>();
foreach (var Name in productName)
{
StatusDetail sd = new StatusDetail();
sd.CarryOver = prdt.Where(a => a.CreatedDate >= from.Date.ToString() && a.ClosedDate <= to.Date.ToShortDateString
}
return Json(statusdetail, JsonRequestBehavior.AllowGet);
}
The comparison of DateTime as string will not be a good option and that wont gives you the exact result, So I recommend you to change the type of CreatedDate and ClosedDate to DateTime. and compare two DateTime values in linq. I think instead of splitting json for creating object of certain types you can use json converters.
Fix for your scenario:
c1.CreatedDate = DateTime.Parse(split[9]);
c1.ClosedDate = DateTime.Parse(split[13]);
Don't forget to change the type in the class, Now its fine to use the linq as like the following:
sd.CarryOver = prdt.Where(a => a.CreatedDate >= from.Date && a.ClosedDate <= to.Date);

How to create complex filter in c# for Magento API

I am trying to create a complex filter in c# to get data from magento API. I already written the following code
MagentoService mservice = new MagentoService();
var mlogin = mservice.login("***", "****");
var result = mservice.storeList(mlogin);
var cpf = new complexFilter[2];
cpf[0] = new complexFilter
{
key = "created_in",
value = new associativeEntity
{
key = "in",
value = "website A"
}
};
cpf[1] = new complexFilter
{
key = "bv_customer_number",
value = new associativeEntity
{
key = "in",
value = "Not Approved"
}
};
var filters = new filters();
filters.complex_filter = cpf;
var result3 = mservice.customerCustomerList(mlogin, filters);
This code works perfect the only issue is I want to add the multiple values in my key = "created_in" with value = "website a", "website b"
Anyone got any ideas on how to properly pass multiple values for a single key?
I solved this problem by aggregating values into 1 value with ',' as separator:
new complexFilter
{
key = "created_in",
value = new associativeEntity
{
key = "in",
value = "websiteA,websiteB,websiteC"
}
};

Create Collection of Anonymous Class

I'm writing a bit of code, and I'd like to play with doing it using the anonymous features of C#.
I'm writing a summary based on a DataTable returned from the SQL Server.
There are many ways I could write it already knowing Classical C# (???), but I'm interested in having a little fun.
So, here are the type of anonymous classes I want to have:
// Employee
var emp = new {
Badge = "000000",
Name = "No Name",
Parts = new List<Part>(),
Days = new List<DateTime>(),
};
// Part
var part = new {
SerialNumber = "N/A",
Date = DateTime.MinValue,
Badge = "000000",
};
Now, as I iterate over my DataTable entries, I want to sort my Parts by SerialNumber.
The first thing I have to do is break the data down into days.
private void TestMethod(DateTime minDate, DateTime maxDate, DataTable table) {
int days = 1;
var nextDay = minDate.AddHours(24);
foreach (DataRow row in table.Rows) {
var dateTime = (DateTime)row["Date_Time"];
var emp = new {
Badge = row["Badge"].ToString(),
Parts = new List<Part>(),
Days = new List<DateTime>(),
};
var part = new {
SerialNumber = row["Serial_Number"].ToString(),
Date = dateTime,
Badge = row["Badge"].ToString(),
};
if (nextDay < dateTime) {
days++;
nextDay = nextDay.AddHours(24);
}
}
Now, it is getting a little interesting.
I need a way to store Part information for the different days and the different employees found for the period.
How would I create and use an anonymous collection of my anonymous class items?
var parts = new List<typeof(part)>();
var emps = new List<typeof(emp)>();
Using typeof (above) does not work!
What does?
You need to use type inference:
new[] { part }.ToList()
(you probably want to clear the list afterwards)
You can also make a helper method:
public static List<T> ListOf<T>(T sample) {
return new List<T>();
}
var parts = ListOf(part);

Linq over InputStream from HttpPostedFileWrapper

Is it possible to apply a Linq query from a HttpPostedFileWrapper?
My web app allows users to select a bunch of .csv files. I now need to open those files and import them.
My previous code, which uses paths and file names looks like;
importedList = (from csvLine in File.ReadAllLines(fileName)
let x = csvLine.Split(',')
select new ImportedXDock
{
StoreNumber = int.Parse(x[0]),
DCNumber = int.Parse(x[1]),
DeliveryDay = x[2],
Activity = x[3],
ActivityDay = x[4],
Time = TimeSpan.Parse(x[5])
}).ToList();
However, now that i have a collection of HttpPostedFileWrapper objects how would I do the same?
edit
Or do I need to convert it to something and then read the file?
You may be able to loop over the file names instead of the input streams
foreach (var fileName in wrapper.Select(w => w.FileName))
{
yield return (from csvLine in File.ReadAllLines(fileName)
let x = csvLine.Split(',')
select new ImportedXDock
{
StoreNumber = int.Parse(x[0]),
DCNumber = int.Parse(x[1]),
DeliveryDay = x[2],
Activity = x[3],
ActivityDay = x[4],
Time = TimeSpan.Parse(x[5])
}).ToList();
}

How to format DateTime comparison value in AX Query Service

I am working with the Dynamics AX 2012 R2 query service and need to filter (set a range) on the modifiedDateTime field of the CustTable. I am creating a QueryDataRangeMetadata object and setting its properties. I can filter properly on integer values but not DateTimes.
I was able to figure out that the comparison operator is actually embedded with the value. I have tested this with integer fields and it does work for but I have not been able to figure out how to format a DateTime value so that it is properly evaluated. The code below doesn't work. The range is simply ignored and all records from the CustTable are returned.
public static void RangeTest()
{
var client = new QueryServiceClient();
var dataSource = new QueryDataSourceMetadata
{
Table = "CustTable",
Name = "CustTable",
HasRelations = false,
Enabled = true,
DynamicFieldList = true // get all fields
};
var range = new QueryDataRangeMetadata
{
TableName = "CustTable",
FieldName = "modifiedDateTime",
Value = ">2013-02-05T21:17:33Z", // <-- ISSUE: notice the operator with the value!
Enabled = true
};
dataSource.Ranges = new QueryRangeMetadata[] { range };
var sort = new QueryDataOrderByMetadata
{
DataSource = "CustTable",
FieldName = "modifiedDateTime",
SortOrder = SortOrder.Ascending
};
var query = new QueryMetadata
{
QueryType = QueryType.Join,
DataSources = new[] { dataSource },
OrderByFields = new QueryOrderByMetadata[] { sort }
};
Paging paging = null;
var dataSet = client.ExecuteQuery(query, ref paging);
Console.WriteLine(dataSet.Tables[0].Rows.Count);
}
I have also tried these formatting variations with no success:
Value = ">2013-02-05 21:17:33"
Value = ">2013-02-05T9:17:33"
Value = ">'2013-02-05T9:17:33'"
Value = ">2013-02-05T21:17:33Z"
Anyone know what the format of the DateTime is supposed to be in this case?
After iterating over a bunch of DateTime formatting variations I just copied and pasted a value from the UI and guess what? It worked. This is the snippet:
var range = new QueryDataRangeMetadata
{
TableName = "CustTable",
FieldName = "modifiedDateTime",
Value = ">2/5/2013 9:17:33 PM",
Enabled = true
};
So the format seems to be: comparison_operatorMM/DD/YYYY hh:mm:ss AM
I am in the US and the format is month-first. I imagine that other locales would have to format differently, e.g. day-first.

Categories