Merge sql into a stored procedure for better performace - c#

I am still having real performance issue in a list there our 38 thousand entrys and I need to map them to another table for export I am thinking of moving it to stored proc but still worried what performance would be like there. The code works but takes a very long time to execute and wish to turn it into a stored proc.
private List<TradeItemsExport> MapTradeItems(List<TradeItems> tradeItem)
{
List<TradeItemsExport> retList = new List<TradeItemsExport>();
try
{
var StockImport = new StockItemExported();
List<StandardLookUpList> _AnalsisCodes = GetAnayalsisCodesForExportCode();
StandardLookUpList sport = new StandardLookUpList();
StandardLookUpList gender = new StandardLookUpList();
StandardLookUpList colour = new StandardLookUpList();
StandardLookUpList Size = new StandardLookUpList();
StandardLookUpList categorycode = new StandardLookUpList();
StandardLookUpList categorydesc = new StandardLookUpList();
StandardLookUpList subcategorycode = new StandardLookUpList();
StandardLookUpList subcategorydesc = new StandardLookUpList();
StandardLookUpList brandcode = new StandardLookUpList();
StandardLookUpList branddesc = new StandardLookUpList();
using (var db = new liveEntities1())
{
int count = 0;
foreach (var item in tradeItem)
{
count++;
bool hasprocessed = HasTransactionBeenProcessed(item.ItemCode);
if (hasprocessed == false)
{
var codesForThisItem = _AnalsisCodes.Where(w => w.ItemCode == item.ItemCode);
if (codesForThisItem.Any())
{
sport = codesForThisItem.FirstOrDefault(x => x.code == Constants.Sport);
gender = codesForThisItem.FirstOrDefault(x => x.code == Constants.Gender);
colour = codesForThisItem.FirstOrDefault(x => x.code == Constants.Colour);
Size = codesForThisItem.FirstOrDefault(x => x.code == Constants.Size);
categorycode = codesForThisItem.FirstOrDefault(x => x.code == Constants.Category);
categorydesc = codesForThisItem.FirstOrDefault(x => x.code == Constants.Category);
subcategorycode = codesForThisItem.FirstOrDefault(x => x.code == Constants.SubCategory);
subcategorydesc = codesForThisItem.FirstOrDefault(x => x.code == Constants.SubCategory);
brandcode = codesForThisItem.FirstOrDefault(x => x.code == Constants.Brand);
string SportCodeValue, SportDescValue;
if (sport == null)
{
SportCodeValue = "";
SportDescValue = "";
}
else
{
SportCodeValue = sport.LookupValue.ToString();
SportDescValue = sport.description;
}
string GenderCodeValue, GenderCodeDesc;
if (gender == null)
{
GenderCodeValue = "";
GenderCodeDesc = "";
}
else
{
GenderCodeValue = gender.LookupValue.ToString();
GenderCodeDesc = gender.description;
}
string ColourCodeValue, ColourCodeDesc;
if (colour == null)
{
ColourCodeValue = "";
ColourCodeDesc = "";
}
else
{
ColourCodeValue = colour.LookupValue.ToString();
ColourCodeDesc = colour.description;
}
string SizeCodeValue, SizeCodeDesc;
if (Size == null)
{
SizeCodeValue = "";
SizeCodeDesc = "";
}
else
{
SizeCodeValue = Size.LookupValue.ToString();
SizeCodeDesc = Size.description;
}
string CategoryCodeValue, CategoryCodeDesc;
if (categorycode == null)
{
CategoryCodeValue = "";
CategoryCodeDesc = "";
}
else
{
CategoryCodeValue = categorycode.LookupValue.ToString();
CategoryCodeDesc = categorydesc.description;
}
string subcategorycodevalue, subcategorycodedesc;
if (categorycode == null)
{
subcategorycodevalue = "";
subcategorycodedesc = "";
}
else
{
subcategorycodevalue = subcategorycode.LookupValue.ToString();
subcategorycodedesc = subcategorydesc.description;
}
string brandcodecodevalue, brandcodecodedesc;
if (brandcode == null)
{
brandcodecodevalue = "";
brandcodecodedesc = "";
}
else
{
brandcodecodevalue = brandcode.LookupValue.ToString();
brandcodecodedesc = brandcode.description;
}
retList.Add(new TradeItemsExport()
{
ItemCode = item.ItemCode,
BarCode = item.BarCode,
Description = item.Description,
SupplierCode = item.SupplierCode,
SupplierStockCode = item.SupplierStockCode,
Product_Group_Code = "",
Product_Group_Desc = "",
SportCode = SportCodeValue,
SportDesc = SportDescValue,
GenderCode = GenderCodeValue,
GenderDesc = GenderCodeDesc,
ColourCode = ColourCodeValue,
ColourDesc = ColourCodeDesc,
SizeCode = SizeCodeValue,
SizeDesc = SizeCodeDesc,
CategoryCode = CategoryCodeValue,
CategoryDesc = CategoryCodeDesc,
subcategorycode = subcategorycodevalue,
subcategorydesc = subcategorycodedesc,
BrandsCode = brandcodecodevalue,
BrandsDesc = brandcodecodedesc,
Vat = item.Vat,
GrossWeight = item.Weight,
CommodityCode = item.CommodityCode,
price_exVAT = item.price_exVAT,
price_incVAT = item.price_incVAT,
currentprice_exVAT = item.currentprice_exVAT,
currentprice_incVAT = item.currentprice_incVAT,
creation_date = item.creation_date,
Inactive_date = item.Inactive_date,
status = 1
});
Console.Write(String.Format("Exporting stock item {0} with a current record of {1} of {2} \n", item.ItemCode.ToString(), count.ToString(), tradeItem.Count.ToString()));
EFStockItemExported _newStockitemImported = new EFStockItemExported();
_newStockitemImported.StockItemID = item.ItemCode;
_newStockitemImported.IsProcessed = true;
_newStockitemImported.DateImported = DateTime.Now;
db.EFStockItemExporteds.Add(_newStockitemImported);
db.SaveChanges();
}
else
{
Console.Write(string.Format("Stock Items to Process [{0}] check the table and remove entry if wish to re process.", 0));
}
}
}
}
}
catch (Exception ex)
{
}
return retList;
}
My problem that this takes around 30 mins to compute the results which is very slow.
This is the sql that I am doing which is a view that is the tradeitem that I am passing.
SELECT
dbo.PLSupplierAccount.SupplierAccountNumber, dbo.PLSupplierAccount.PLSupplierAccountID, dbo.PLSupplierAccount.SupplierAccountName,
dbo.PLSupplierAccount.SYSCurrencyID, dbo.PLSupplierAccount.MainTelephoneAreaCode, dbo.PLSupplierAccount.MainTelephoneCountryCode,
dbo.PLSupplierAccount.MainTelephoneSubscriberNumber, dbo.PLSupplierAccount.MainFaxCountryCode, dbo.PLSupplierAccount.MainFaxSubscriberNumber,
dbo.PLSupplierAccount.MainFaxAreaCode, dbo.PLSupplierContact.ContactName, dbo.PLSupplierContact.Description, dbo.PLSupplierContact.FirstName,
dbo.PLSupplierContact.MiddleName, dbo.PLSupplierContact.LastName, loc.AddressLine1, loc.AddressLine2, loc.AddressLine3, loc.AddressLine4, loc.PostCode,
loc.City, loc.County,
CAST(CASE WHEN loc.Country = 'Ireland' THEN 'IRL'
WHEN loc.Country = 'Great Britain'
THEN 'GBR'
ELSE 'ERR'
END AS nvarchar(3)) AS Country,
dbo.SYSCurrency.SYSCurrencyISOCodeID, dbo.SYSCurrency.SYSExchangeRateTypeID, dbo.SYSCurrency.Name AS CurrencyDescription,
dbo.SYSCurrency.Symbol AS CurrencySymbol
FROM
dbo.PLSupplierAccount
INNER JOIN
dbo.PLSupplierContact ON dbo.PLSupplierAccount.PLSupplierAccountID = dbo.PLSupplierContact.PLSupplierAccountID
INNER JOIN
dbo.PLSupplierLocation AS loc ON dbo.PLSupplierAccount.PLSupplierAccountID = loc.PLSupplierAccountID
AND dbo.PLSupplierContact.PLSupplierLocationID = loc.PLSupplierLocationID
INNER JOIN
dbo.SYSCurrency ON dbo.PLSupplierAccount.SYSCurrencyID = dbo.SYSCurrency.SYSCurrencyID
My quesiton is how would I change the above to include a sub query that would do the same as this function is doing above.
The query for the codes look up which is again another view is below.
SELECT
dbo.StockItem.ItemID, dbo.StockItem.Code, dbo.StockItem.Name, dbo.StockItemSearchCatVal.SearchValueID, dbo.SearchValue.Name AS Expr1,
dbo.SearchCategory.Name AS Expr2
FROM
dbo.SearchCategory
INNER JOIN
dbo.SearchValue ON dbo.SearchCategory.SearchCategoryID = dbo.SearchValue.SearchCategoryID
INNER JOIN
dbo.StockItemSearchCatVal ON dbo.SearchCategory.SearchCategoryID = dbo.StockItemSearchCatVal.SearchCategoryID
AND dbo.SearchValue.SearchValueID = dbo.StockItemSearchCatVal.SearchValueID
INNER JOIN
dbo.StockItem ON dbo.StockItemSearchCatVal.ItemID = dbo.StockItem.ItemID
I just feel I would get more benefit changing this into a subquery so that I am just returning the results to .net I am using the filehelpers library to output the results set of MapTradeItems to csv so obv more things I can do the better on the server.
Obv I would need some kind of temporary table to loop through the results but how quick would that be in sql server compared to a .net for each loop.
This is the poco class which I have to reproduce to csv.
[DelimitedRecord(",")]
public class TradeItemsExport
{
[FieldOrder(1)]
public string ItemCode { get; set; }
[FieldOrder(2)]
public string BarCode { get; set; }
[FieldOrder(3)]
public string Description { get; set; }
[FieldOrder(4)]
public string SupplierCode { get; set; }
[FieldOrder(5)]
public string SupplierStockCode { get; set; }
[FieldOrder(6)]
public string Product_Group_Code { get; set; }
[FieldOrder(7)]
public string Product_Group_Desc { get; set; }
[FieldOrder(8)]
public string SportCode { get; set; }
[FieldOrder(9)]
public string SportDesc { get; set; }
[FieldOrder(10)]
public string GenderCode { get; set; }
[FieldOrder(11)]
public string GenderDesc { get; set; }
[FieldOrder(12)]
public string ColourCode { get; set; }
[FieldOrder(13)]
public string ColourDesc { get; set; }
[FieldOrder(14)]
public string SizeCode { get; set; }
[FieldOrder(15)]
public string SizeDesc { get; set; }
[FieldOrder(16)]
public string CategoryCode { get; set; }
[FieldOrder(17)]
public string CategoryDesc { get; set; }
[FieldOrder(18)]
public string subcategorycode { get; set; }
[FieldOrder(19)]
public string subcategorydesc { get; set; }
[FieldOrder(20)]
public string BrandsCode { get; set; }
[FieldOrder(21)]
public string BrandsDesc { get; set; }
[FieldOrder(22)]
public Nullable<short> Vat { get; set; }
[FieldOrder(23)]
public decimal GrossWeight { get; set; }
[FieldOrder(24)]
public string CommodityCode { get; set; }
[FieldOrder(25)]
public decimal price_exVAT { get; set; }
[FieldOrder(26)]
public Nullable<decimal> price_incVAT { get; set; }
[FieldOrder(27)]
public Nullable<decimal> currentprice_exVAT { get; set; }
[FieldOrder(28)]
public Nullable<decimal> currentprice_incVAT { get; set; }
[FieldOrder(29)]
public System.DateTime creation_date { get; set; }
[FieldOrder(30)]
public Nullable<System.DateTime> Inactive_date { get; set; }
[FieldOrder(31)]
public int status { get; set; }
}

Related

MVC Controller Action/dll only works in localhost

I have an MVC that takes values from a form, sends them to a dll, to have logic performed on them & assigned to a model. The model is then returned to the view. In localhost it is successful and I get the following result:
However when I publish the webapp to an azure instance, it doesn't return any of the values. You can see it here: http://levelupsite.azurewebsites.net/ or see the image here
Does anyone know what could cause this? I will attach the code below:
Controller:
[HttpPost]
public ActionResult CBC(System.Web.Mvc.FormCollection form, FFAC model)
{
//recieve values from form
var email = escapeCharactersspace((form["email"].ToString()));
var Gender = Convert.ToString(model.UserGender);
var UserID = escapeCharactersspace((form["username"].ToString()));
var Neutrophils = escapeCharactersspace(form["Neutrophils"]);
var Lymphocytes = escapeCharactersspace(form["Lympthocytes"]);
var Monocytes = escapeCharactersspace(form["Monocytes"]);
var Eosinophils = escapeCharactersspace(form["Eosinophils"]);
var Basophils = escapeCharactersspace(form["Basophils"]);
var Platelets = (escapeCharactersspace(form["Platelets"]));
var Haematocrit = escapeCharactersspace(form["Haematocrit"]);
var Haemoglobin = escapeCharactersspace(form["Haemoglobin"]);
var MCV = escapeCharactersspace(form["MCV"]);
var MCH = (escapeCharactersspace(form["MCH"]));
var MCHC = escapeCharactersspace(form["MCHC"]);
//turn form to array
decimal[] cbcInputs = { Convert.ToDecimal(Neutrophils), Convert.ToDecimal(Lymphocytes), Convert.ToDecimal(Monocytes), Convert.ToDecimal(Eosinophils), Convert.ToDecimal(Basophils), Convert.ToDecimal(Platelets), Convert.ToDecimal(Haematocrit), Convert.ToDecimal(Haemoglobin), Convert.ToDecimal(MCV), Convert.ToDecimal(MCH), Convert.ToDecimal(MCHC) };
//create instance of model
var scfiae = new FIAECBC();
//create instance of external class library
var fiae = new FIAEngine();
//send inputs & model instance to external class library to perform logic
fiae.setcbcvals(cbcInputs, UserID, Gender, scfiae);
//return the get results page
return View("GetResults", scfiae);
}
FIAEngine - dll that performs the logic
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SharedComponents;
using static SharedComponents.FIAECBC;
namespace FIAE
{
public class FIAEngine
{
decimal d_Neutrophils;
decimal d_Lymphocytes;
decimal d_Monocytes;
decimal d_Eosinophils;
decimal d_Basophils;
decimal d_Platelets;
decimal d_Haematocrit;
decimal d_Haemoglobin;
decimal d_MCV;
decimal d_MCH;
decimal d_MCHC;
string UserID;
string Gender;
string Neutrophils;
string Lymphocytes;
string Monocytes;
string Eosinophils;
string Basophils;
string Platelets;
string Haematocrit;
string Haemoglobin;
string MCV;
string MCH;
string MCHC;
string rag_Neutrophils;
string rag_Lymphocytes;
string rag_Monocytes;
string rag_Eosinophils;
string rag_Basophils;
string rag_Platelets;
string rag_Haematocrit;
string rag_Haemoglobin;
string rag_MCV;
string rag_MCH;
string rag_MCHC;
public void Setcbcfilevals(FIAECBC cbcmodel)
{
}
public void setcbcvals(decimal[] inputs, string _UserID, string _Gender, FIAECBC cbcmodel)
{
d_Neutrophils = inputs[0];
d_Lymphocytes = inputs[1];
d_Monocytes = inputs[2];
d_Eosinophils = inputs[3];
d_Basophils = inputs[4];
d_Platelets = inputs[5];
d_Haematocrit = inputs[6];
d_Haemoglobin = inputs[7];
d_MCV = inputs[8];
d_MCH = inputs[9];
d_MCHC = inputs[10];
UserID = _UserID;
Gender = _Gender;
Neutrophils = "Neutrophils";
Lymphocytes = "Lymphocytes";
Monocytes = "Monocytes";
Eosinophils = "Eosinophils";
Basophils = "Basophils";
Platelets = "Platelets";
Haematocrit = "Haematocrit";
Haemoglobin = "Haemoglobin";
MCV = "MCV";
MCH = "MCH";
MCHC = "MCHC";
rag_Neutrophils = "i";
rag_Lymphocytes = "i";
rag_Monocytes = "i";
rag_Eosinophils = "i";
rag_Basophils = "i";
rag_Platelets = "i";
rag_Haematocrit = "i";
rag_Haemoglobin = "i";
rag_MCV = "i";
rag_MCH = "i";
rag_MCHC = "i";
try
{
//male calculations
if (Gender == "Male")
{
rag_Neutrophils = FindMaleRAG(d_Neutrophils, 1);
rag_Lymphocytes = FindMaleRAG(d_Lymphocytes, 2);
rag_Monocytes = FindMaleRAG(d_Monocytes, 3);
rag_Eosinophils = FindMaleRAG(d_Eosinophils, 4);
rag_Basophils = FindfeMaleRAG(d_Basophils, 5);
rag_Platelets = FindMaleRAG(d_Platelets, 6);
rag_Haematocrit = FindMaleRAG(d_Haematocrit, 7);
rag_Haemoglobin = FindMaleRAG(d_Haemoglobin, 8);
rag_MCV = FindMaleRAG(d_MCV, 9);
rag_MCH = FindMaleRAG(d_MCH, 10);
rag_MCHC = FindMaleRAG(d_MCHC, 11);
//set view model values to the form values
cbcmodel.d_Neutrophils = d_Neutrophils;
cbcmodel.d_Lymphocytes = d_Lymphocytes;
cbcmodel.d_Monocytes = d_Monocytes;
cbcmodel.d_Eosinophils = d_Eosinophils;
cbcmodel.d_Basophils = d_Basophils;
cbcmodel.d_Platelets = d_Platelets;
cbcmodel.d_Haematocrit = d_Haematocrit;
cbcmodel.d_Haemoglobin = d_Haemoglobin;
cbcmodel.d_MCV = d_MCV;
cbcmodel.d_MCH = d_MCH;
cbcmodel.d_MCHC = d_MCHC;
cbcmodel.Neutrophils = Neutrophils;
cbcmodel.Lymphocytes = Lymphocytes;
cbcmodel.Monocytes = Monocytes;
cbcmodel.Eosinophils = Eosinophils;
cbcmodel.Basophils = Basophils;
cbcmodel.Platelets = Platelets;
cbcmodel.Haematocrit = Haematocrit;
cbcmodel.Haemoglobin = Haemoglobin;
cbcmodel.MCV = MCV;
cbcmodel.MCH = MCH;
cbcmodel.MCHC = MCHC;
cbcmodel.rag_Neutrophils = rag_Neutrophils;
cbcmodel.rag_Lymphocytes = rag_Lymphocytes;
cbcmodel.rag_Monocytes = rag_Monocytes;
cbcmodel.rag_Eosinophils = rag_Eosinophils;
cbcmodel.rag_Basophils = rag_Basophils;
cbcmodel.rag_Platelets = rag_Platelets;
cbcmodel.rag_Haematocrit = rag_Haematocrit;
cbcmodel.rag_Haemoglobin = rag_Haematocrit;
cbcmodel.rag_MCV = rag_MCV;
cbcmodel.rag_MCH = rag_MCH;
cbcmodel.rag_MCHC = rag_MCHC;
}
else if (Gender == "Female")
{
rag_Neutrophils = FindfeMaleRAG(d_Neutrophils, 1);
rag_Lymphocytes = FindfeMaleRAG(d_Lymphocytes, 2);
rag_Monocytes = FindfeMaleRAG(d_Monocytes, 3);
rag_Eosinophils = FindfeMaleRAG(d_Eosinophils, 4);
rag_Basophils = FindfeMaleRAG(d_Basophils, 5);
rag_Platelets = FindfeMaleRAG(d_Platelets, 6);
rag_Haematocrit = FindfeMaleRAG(d_Haematocrit, 7);
rag_Haemoglobin = FindfeMaleRAG(d_Haemoglobin, 8);
rag_MCV = FindfeMaleRAG(d_MCV, 9);
rag_MCH = FindfeMaleRAG(d_MCH, 10);
rag_MCHC = FindfeMaleRAG(d_MCHC, 11);
//set view model values to the form values
cbcmodel.d_Neutrophils = d_Neutrophils;
cbcmodel.d_Lymphocytes = d_Lymphocytes;
cbcmodel.d_Monocytes = d_Monocytes;
cbcmodel.d_Eosinophils = d_Eosinophils;
cbcmodel.d_Basophils = d_Basophils;
cbcmodel.d_Platelets = d_Platelets;
cbcmodel.d_Haematocrit = d_Haematocrit;
cbcmodel.d_Haemoglobin = d_Haemoglobin;
cbcmodel.d_MCV = d_MCV;
cbcmodel.d_MCH = d_MCH;
cbcmodel.d_MCHC = d_MCHC;
cbcmodel.Neutrophils = Neutrophils;
cbcmodel.Lymphocytes = Lymphocytes;
cbcmodel.Monocytes = Monocytes;
cbcmodel.Eosinophils = Eosinophils;
cbcmodel.Basophils = Basophils;
cbcmodel.Platelets = Platelets;
cbcmodel.Haematocrit = Haematocrit;
cbcmodel.Haemoglobin = Haemoglobin;
cbcmodel.MCV = MCV;
cbcmodel.MCH = MCH;
cbcmodel.MCHC = MCHC;
cbcmodel.rag_Neutrophils = rag_Neutrophils;
cbcmodel.rag_Lymphocytes = rag_Lymphocytes;
cbcmodel.rag_Monocytes = rag_Monocytes;
cbcmodel.rag_Eosinophils = rag_Eosinophils;
cbcmodel.rag_Basophils = rag_Basophils;
cbcmodel.rag_Platelets = rag_Platelets;
cbcmodel.rag_Haematocrit = rag_Haematocrit;
cbcmodel.rag_Haemoglobin = rag_Haematocrit;
cbcmodel.rag_MCV = rag_MCV;
cbcmodel.rag_MCH = rag_MCH;
cbcmodel.rag_MCHC = rag_MCHC;
}
}
catch (Exception ex)
{
}
//return inputs;
}
public string FindMaleRAG(decimal i, int x)
{
String connString = Convert.ToString(ConfigurationManager.ConnectionStrings["SQLServerCon"]);
//for each row, do this
//find the threshld values
String thresholdquery = #"select * from dbo.malethreshold where ID = " + x;
using (var conn = new SqlConnection(connString))
{
conn.Open();
using (SqlCommand command = new SqlCommand(thresholdquery, conn))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
//compare threshold values t posted values from form
string composite = Convert.ToString(reader[1]);
decimal redlow = Convert.ToDecimal(reader[2]);
decimal greenlow = Convert.ToDecimal(reader[3]);
decimal greenhigh = Convert.ToDecimal(reader[4]);
decimal redhigh = Convert.ToDecimal(reader[5]);
if (i < redlow)
{
// Red low
return ("red");
}
else if (i > redlow && i < greenlow)
{
// Amber Low
return ("orange");
}
else if (i >= greenlow && i <= greenhigh)
{
//green
return ("green");
}
else if (i > greenhigh && i < redhigh)
{
//amber high
return ("orange");
}
else if (i > redhigh)
{
// Redhigh
return ("red");
}
else
{
//sorting error
return ("error in sorting");
}
}
}
}
}
return ("sorting error");
}
public string FindfeMaleRAG(decimal i, int x)
{
String connString = Convert.ToString(ConfigurationManager.ConnectionStrings["SQLServerCon"]);
//for each row, do this
//find the threshld values
String thresholdquery = #"select * from dbo.malethreshold where ID = " + x;
using (var conn = new SqlConnection(connString))
{
conn.Open();
using (SqlCommand command = new SqlCommand(thresholdquery, conn))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
//compare threshold values t posted values from form
string composite = Convert.ToString(reader[1]);
decimal redlow = Convert.ToDecimal(reader[2]);
decimal greenlow = Convert.ToDecimal(reader[3]);
decimal greenhigh = Convert.ToDecimal(reader[4]);
decimal redhigh = Convert.ToDecimal(reader[5]);
if (i < redlow)
{
// Red low
return ("red");
}
else if (i > redlow && i < greenlow)
{
// Amber Low
return ("orange");
}
else if (i >= greenlow && i <= greenhigh)
{
//green
return ("green");
}
else if (i > greenhigh && i < redhigh)
{
//amber high
return ("orange");
}
else if (i > redhigh)
{
// Redhigh
return ("red");
}
else
{
//sorting error
return ("error in sorting");
}
}
}
}
}
return ("sorting error");
}
}
}
FIAECBC model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
namespace SharedComponents
{
public class FIAECBC
{
public string Neutrophils { get; set; }
public string Lymphocytes { get; set; }
public string Monocytes { get; set; }
public string Eosinophils { get; set; }
public string Basophils { get; set; }
public string Platelets { get; set; }
public string Haematocrit { get; set; }
public string Haemoglobin { get; set; }
public string MCV { get; set; }
public string MCH { get; set; }
public string MCHC { get; set; }
public decimal d_Neutrophils { get; set; }
public decimal d_Lymphocytes { get; set; }
public decimal d_Monocytes { get; set; }
public decimal d_Eosinophils { get; set; }
public decimal d_Basophils { get; set; }
public decimal d_Platelets { get; set; }
public decimal d_Haematocrit { get; set; }
public decimal d_Haemoglobin { get; set; }
public decimal d_MCV { get; set; }
public decimal d_MCH { get; set; }
public decimal d_MCHC { get; set; }
public string rag_Neutrophils { get; set; }
public string rag_Lymphocytes { get; set; }
public string rag_Monocytes { get; set; }
public string rag_Eosinophils { get; set; }
public string rag_Basophils { get; set; }
public string rag_Platelets { get; set; }
public string rag_Haematocrit { get; set; }
public string rag_Haemoglobin { get; set; }
public string rag_MCV { get; set; }
public string rag_MCH { get; set; }
public string rag_MCHC { get; set; }
public Gender UserGender { get; set; }
public static IEnumerable<SelectListItem> GetSelectItems()
{
yield return new SelectListItem { Text = "Male", Value = "Male" };
yield return new SelectListItem { Text = "Female", Value = "Female" };
}
public bool Bookkeeping { get; set; }
}
public enum Gender
{
Male,
Female
}
}

Elastic search nest dynamic query with object initializer NEST 5.x

Hi I'm a new to elastic nest API and I'm using nest 5.x. I'm currently developing some kind of advanced search page so when user doesn't check a criteria i don't have to include that filter on my query. I'm trying to combine 2 queries under must operator with object initializer approach using nest. How to achieve it? I'm following the example on [https://www.elastic.co/guide/en/elasticsearch/client/net-api/current/bool-queries.html]
var secondSearchResponse = client.Search(new
SearchRequest {
Query = new TermQuery { Field = Field(p => p.Name), Value = "x" } &&
new TermQuery { Field = Field(p => p.Name), Value = "y" } });
But it doesnt work cause Field class doesnt accept type arguments.
I also tried to followed this approach from this topic
[Nest Elastic - Building Dynamic Nested Query
here is my code
public HttpResponseMessage GetSearchResult([FromUri] SearchModels queries)
{
try
{
///
string result = string.Empty;
result += "queryfields + " + queries.queryfields == null ? string.Empty : queries.queryfields;
result += "datefrom + " + queries.datefrom == null ? string.Empty : queries.datefrom;
result += "dateto + " + queries.dateto == null ? string.Empty : queries.dateto;
result += "emitentype + " + queries.emitentype == null ? string.Empty : queries.emitentype;
QueryContainer andQuery = null;
//List<QueryContainer> QueryContainers = new List<QueryContainer>();
IDXNetAnnouncement record = new IDXNetAnnouncement
{
kode_emiten = queries.kodeemiten
};
#region keyword
if (!string.IsNullOrEmpty(queries.queryfields))
{
var val = queries.queryfields;
TermQuery tq = new TermQuery
{
Field = queries.queryfields,
Value = val
};
if (andQuery == null)
andQuery = tq;
else
andQuery &= tq;
//QueryContainers.Add(tq);
}
#endregion keyword
#region kodeemiten
if (!string.IsNullOrEmpty(queries.kodeemiten))
{
var val = queries.kodeemiten;
TermQuery tq = new TermQuery
{
Name = "kode_emiten",
Field = record.kode_emiten,
Value = val
};
if (andQuery == null)
andQuery = tq;
else
andQuery &= tq;
//QueryContainers.Add(tq);
}
#endregion
#region date
if (!string.IsNullOrEmpty(queries.datefrom) && !string.IsNullOrEmpty(queries.dateto))
{
DateRangeQuery dq = new DateRangeQuery();
dq.Name = "tglpengumuman";
dq.LessThanOrEqualTo = DateMath.Anchored(queries.dateto);
dq.GreaterThanOrEqualTo = DateMath.Anchored(queries.datefrom);
dq.Format = "dd/mm/yyyy";
if (andQuery == null)
andQuery = dq;
else
andQuery &= dq;
//QueryContainers.Add(dq);
}
#endregion keyword
var reqs = (ISearchResponse<IDXNetAnnouncement>)null;
if (andQuery != null)
{
reqs = conn.client.Search<IDXNetAnnouncement>(s => s
.AllIndices()
.AllTypes()
.From(queries.indexfrom)
.Size(queries.pagesize)
.Query(q => q.Bool(qb => qb.Must(m => m.MatchAll() && andQuery))));
//var json = conn.client.Serializer.SerializeToString(reqs.ApiCall.ResponseBodyInBytes);
}
else
{
reqs = conn.client.Search<IDXNetAnnouncement>(s => s
.AllIndices()
.AllTypes()
.From(queries.indexfrom)
.Size(queries.pagesize)
.Query(m => m.MatchAll()));
}
//var reqstring = Encoding.UTF8.GetString(conn.client.);
var reslts = this.conn.client.Serializer.SerializeToString(reqs,SerializationFormatting.Indented);
var resp = new HttpResponseMessage()
{
Content = new StringContent(reslts)
};
resp.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return resp;
}
catch (Exception e)
{
var resp = new HttpResponseMessage()
{
Content = new StringContent(e.ToString())
};
resp.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return resp;
}
}
But that returns zero result. How to achieve this? Thx anyway.
EDIT :
This is the params variabel definition. Its apoco model of search keywords
public class SearchModels
{
public string queryfields { get; set; }
public string datefrom { get; set; }
public string dateto { get; set; }
public string emitentype { get; set; }
public string kodeemiten { get; set; }
public string issuercode { get; set; }
public int indexfrom { get; set; }
public int pagesize { get; set; }
}
IDXNetAnnouncement is a poco model of search result. Its actualy a document type which is stored on the elastic server
public class IDXNetAnnouncement
{
public string perihalpengumuman { get; set; }
public string attachments { get; set; }
public string createddate { get; set; }
public bool efekemiten_spei { get; set; }
public string jmsxgroupid { get; set; }
public string tglpengumuman { get; set; }
public object errordescription { get; set; }
public string ESversion { get; set; }
public int oldfinalid { get; set; }
public bool efekemiten_etf { get; set; }
public object errorcode { get; set; }
public string jenisemiten { get; set; }
public int pkid { get; set; }
public string judulpengumuman { get; set; }
public string form_id { get; set; }
public bool efekemiten_eba { get; set; }
public string jenispengumuman { get; set; }
public string nopengumuman { get; set; }
public string kode_emiten { get; set; }
public string divisi { get; set; }
public string EStimestamp { get; set; }
public bool efekemiten_obligasi { get; set; }
public long finalid { get; set; }
public bool efekemiten_saham { get; set; }
public string kodedivisi { get; set; }
public string SearchTerms
{
get
{
return string.Format("{0} {1} {2}", judulpengumuman, kode_emiten, nopengumuman);
}
}
}
But it doesnt work cause Field class doesnt accept type arguments.
You need to ensure that you include a using static directive for Nest.Infer i.e.
using static Nest.Infer;
with the rest of the using directives.
.Query(q => q.Bool(qb => qb.Must(m => m.MatchAll() && andQuery))));
No need to wrap in a Must(), just do
.Query(q => q.MatchAll() && andQuery)
which will wrap both queries in a bool query must clause. You also don't need to null check andQuery because NEST is smart enough to not combine the two queries if either or both are null.
if (!string.IsNullOrEmpty(queries.queryfields))
{
var val = queries.queryfields;
TermQuery tq = new TermQuery
{
Field = queries.queryfields,
Value = val
};
if (andQuery == null)
andQuery = tq;
else
andQuery &= tq;
//QueryContainers.Add(tq);
}
NEST has the concept of conditionless queries so you don't need to check it queries.queryfields is null or empty, simply build the query and add it to andQuery. So it would become
var val = queries.queryfields;
andQuery &= new TermQuery
{
Field = queries.queryfields,
Value = val
};
Aside
All of the NEST documentation is generated from source code; you can trace back to the original source file by clicking on any edit link within the documentation. This will take you to a github page, such as this one for bool queries. From here, the document contains an important note that links back to the original source.

Find Unique count on field using LINQ

I am trying to determine the Distinct count for a particular field in a collection of objects.
private static RemittanceCenterBatchSummaryListModel SummarizeFields(RemittanceCenterSummaryListModel remittanceCenterSummaryListModel)
{
var result = remittanceCenterSummaryListModel.RemittanceBatchSummaryRecord.GroupBy(x => new{x.FileId, x.SourceFileName, x.BatchCode, x.BatchType})
.Select(x => new RemittanceCenterBatchSummarizedModel()
{
FileId = x.Key.FileId,
SourceFileName = x.Key.SourceFileName,
BatchCode = x.Key.BatchCode,
BatchType = x.Key.BatchType,
DetailRecordCountAdc = x.Count(y => y.BillingSystemCode == BillingSystemCode.Adc),
DetailRecordCountNotAdc = x.Count(y => y.BillingSystemCode == BillingSystemCode.Exd),
AmountAdc = x.Where(y => y.BillingSystemCode == BillingSystemCode.Adc).Sum(y => y.PaymentAmount),
AmountNotAdc = x.Where(y => y.BillingSystemCode == BillingSystemCode.Exd).Sum(y => y.PaymentAmount),
UniqueFileCount = x.Select(y => x.Key.FileId).Distinct().Count()
});
return CreateSummaryListModel(result);
}
Input entities:
public class RemittanceCenterSummaryListModel
{
public RemittanceCenterSummaryListModel()
{
this.RemittanceBatchSummaryRecord = new List<RemittanceBatchProcessingModel>();
}
public List<RemittanceBatchProcessingModel> RemittanceBatchSummaryRecord { get; private set; }
}
public class RemittanceCenterBatchSummarizedModel
{
public string FileId { get; set; }
public string SourceFileName { get; set; }
public string BatchCode { get; set; }
public string BatchType { get; set; }
public int DetailRecordCountAdc { get; set; }
public int DetailRecordCountNotAdc { get; set; }
public int DetailRecordCountTotal { get; set; }
public decimal AmountAdc { get; set; }
public decimal AmountNotAdc { get; set; }
public decimal AmountTotal { get; set; }
public BillingSystemCode BillingSystemCode { get; set; }
public int UniqueFileCount { get; set; }
}
private static RemittanceCenterBatchSummaryListModel CreateSummaryListModel(IEnumerable<RemittanceCenterBatchSummarizedModel> summaryModels)
{
var summaryModelList = new RemittanceCenterBatchSummaryListModel();
foreach (var summaryRec in summaryModels)
{
var summaryModel = new RemittanceCenterBatchSummarizedModel
{
FileId = summaryRec.FileId,
SourceFileName = summaryRec.SourceFileName,
BatchCode = summaryRec.BatchCode,
BatchType = summaryRec.BatchType,
DetailRecordCountAdc = summaryRec.DetailRecordCountAdc,
DetailRecordCountNotAdc = summaryRec.DetailRecordCountNotAdc,
AmountAdc = summaryRec.AmountAdc,
AmountNotAdc = summaryRec.AmountNotAdc,
UniqueFileCount = summaryRec.UniqueFileCount
};
summaryModelList.RemittanceBatchSummary.Add(summaryModel);
}
return summaryModelList;
}
Example input records:
Record1:
FileId: '123'
SourceFileName: 'test.file.txt'
BatchCode: 'aaa'
BatchType: 'scanned'
PaymentAmount: '50.00'
BillingSystemCode: 'Adc'
Record1:
FileId: '1234'
SourceFileName: 'test.file2.txt'
BatchCode: 'aab'
BatchType: 'scanned'
PaymentAmount: '52.00'
BillingSystemCode: 'Adc'
ActualOuput for UniqueFileCount Field:
UniqueFileCount = 1
ExpectedOutput results for UniqueFileCount Field:
UniqueFileCount = 2
What am I doing wrong?
It sounds like you want the distinct count of FileId for the entire collection and not just for each group, which will always be 1 since FileId is one of the fields you group on. If that is the case then you can just calculate that count first
int distinctFileIds = remittanceCenterSummaryListModel.RemittanceBatchSummaryRecor‌​d
.Select(x => x.FileId)
.Distinct()
.Count();
Then use that in your Linq query
UniqueFileCount = distinctFileIds

Creating a progress bar for SQL query (using ADO.NET)

I'm trying to make a progress bar for my SQL query but don't know where to start. I have tried implementing the backgroundworker but I can't seem to get it to work.
I'm using VS 2010 .NET 4.0
Treinen trein = listboxVoertuigNr.SelectedItem as Treinen;
List<string> treinenIds = new List<string>();
foreach (var item in listboxVoertuigNr.SelectedItems)
{
treinenIds.Add(item.ToString());
}
fouten = eventsEntities.Foutens;
category = eventsEntities.Category_MMAP;
IEnumerable<dynamic> FoutenResultaat = new List<dynamic>();
FoutenResultaat =
(from x in treinen
join fout in fouten
on x.TreinId equals fout.TreinId
where dateStart <= fout.Datum && dateEnd >= fout.Datum
&& treinenIds.Contains(fout.Treinen.Name)
&& fout.Omschrijving.Contains(textboxFilterOmschrijving.Text)
&& fout.FoutCode.Contains(textboxFilterFout.Text)
&& fout.Module.Contains(textboxFilterModule.Text)
orderby fout.Datum descending, fout.Time descending
join cat in category
on fout.FoutCode equals cat.Foutcode
select new
{
Datum = fout.Datum,
Time = fout.Time,
FoutCode = fout.FoutCode,
Omschrijving = fout.Omschrijving,
Module = fout.Module.ToUpper(),
FoutId = fout.FoutId,
Name = x.Name,
Category = cat.Cat_MMAP
});
GetGraad(FoutenResultaat);
In GetGraad() the read data from the SQL database gets placed in a list. This is a custom list because it also gets populated with values from a excel file.
private void GetGraad(IEnumerable<dynamic> mijnResultaten)
{
foreach (dynamic item in mijnResultaten)
{
string graad = "";
string Toolbox = "";
if (item.Module.Contains("_"))
modNaam = item.Module.Split('_');
else if (item.Module.Contains(" "))
modNaam = item.Module.Split(' ');
string compare = modNaam[0].Substring(0, modNaam[0].Length - 1).ToString();
if (compare == "MPU")
{
var index = Properties.Settings.Default.listFoutcodeMPU.FindIndex(a => a == item.FoutCode);
if (index == -1)
graad = "";
else
{
graad = Properties.Settings.Default.listGraadMPU[index];
Toolbox = Properties.Settings.Default.listToolboxMPU[index];
}
}
if (compare == "AAUX")
{
var index = Properties.Settings.Default.listFoutcodeAAUX.FindIndex(a => a == item.FoutCode);
if (index == -1)
graad = "";
else
{
Toolbox = Properties.Settings.Default.listToolboxAAUX[index];
graad = Properties.Settings.Default.listGraadAAUX[index];
}
}
if (compare == "CTRL")
{
var index = Properties.Settings.Default.listFoutcodeCTRL.FindIndex(a => a == item.FoutCode);
if (index == -1)
graad = "";
else
{
Toolbox = Properties.Settings.Default.listToolboxACTRL[index];
graad = Properties.Settings.Default.listGraadCTRL[index];
}
}
string cat = Convert.ToString(item.Category);
if (cat == null)
cat = "Onbeschikbaar";
try
{
dataTreinFouten.Add(new FoutenMetNaam { Datum = item.Datum, FoutCode = item.FoutCode, Module = modNaam[0].ToUpper(), File = modNaam[1].ToUpper(), Name = item.Name, Omschrijving = item.Omschrijving, Time = item.Time, Graad = graad, FoutId = item.FoutId, Toolbox = Toolbox, Category = cat.ToUpper()});
}
catch (Exception ex)
{
Xceed.Wpf.Toolkit.MessageBox.Show(ex.Message);
}
}
}
The list is used to populate a datagrid, the class used for the list "dataTreinFouten":
class FoutenMetNaam
{
public DateTime Datum { get; set; }
public TimeSpan Time { get; set; }
public String FoutCode { get; set; }
public String Omschrijving { get; set; }
public String Module { get; set; }
public String Name { get; set; }
public int FoutId { get; set; }
public string Graad { get; set; }
public string File { get; set; }
public List<ExtraInfo> listInfoRondFout { get; set; }
public bool isManueel { get; set; }
public string Toolbox { get; set; }
public string Category { get; set; }
}
But I can't really get the state of how far the query is already. Which means I can't update a progress bar with it current state and because the database can contain over 30.000.000 results it is quite needed.
EDIT:
I added a Entity Data Model generated from my SQL database "Events".
Code to use this:
private EventsEntities eventsEntities = new EventsEntities();
Any help or pointing in the right direction is greatly appreciated!

max and group by question with LINQ

I want to group the below query by GetSetDomainName and select the row which has the maximum GetSetKalanGun.In other words, I am trying to get the row with the maximum KALANGUN among those which have the same DOMAINNAME.
var kayitlar3 = (
from rows in islemDetayKayitListesi
select new
{
KAYITNO = rows.GetSetKayitNo,
HESAPADI = rows.GetSetHesapAdi,
URUNNO = rows.GetSetUrunNo,
URUNADI = rows.GetSetUrunAdi,
URUNMIKTAR = rows.GetSetUrunMiktar,
ISLEMTARIHI = rows.GetSetIslemTarihi,
HIZMETDURUMU = rows.GetSetHizmetDurumu,
TOPLAMTUTAR = rows.GetSetToplamTutar,
HIZMETBASLANGICTARIHI = rows.GetSetHizmetBaslangicTarihi,
HIZMETBITISTARIHI = rows.GetSetHizmetBitisTarihi,
KALANGUN = rows.GetSetKalanGun
DOMAINNAME = rows.GetSetDomainName,
SIPARISDURUMU = rows.GetSetSiparisDurumu
}).AsQueryable();
This is what I get
KAYITNO DOMAINNAME KALANGUN
1 asdf.com 30
2 domnam.com 172
3 asdf.com 40
4 xyz.com 350
This is what I want
KAYITNO DOMAINNAME KALANGUN
2 domnam.com 172
3 asdf.com 40
4 xyz.com 350
var islemDetayKayitListesi = new List<IslemDetayKayit>();
islemDetayKayitListesi get filled with a foreach loop, with no problem
And that is what IslemDetayKayit looks like
public class IslemDetayKayit
{
public int GetSetKayitNo { get; set; }
public string GetSetHesapAdi { get; set; }
public string GetSetUrunNo { get; set; }
public string GetSetUrunAdi { get; set; }
public double GetSetUrunMiktar { get; set; }
public string GetSetIslemTarihi { get; set; }
public string GetSetHizmetDurumu { get; set; }
public string GetSetToplamTutar { get; set; }
public string GetSetHizmetBaslangicTarihi { get; set; }
public string GetSetHizmetBitisTarihi { get; set; }
public int GetSetKalanGun { get; set; }
public string GetSetSiparisDurumu { get; set; }
public string GetSetDomainName { get; set; }
}
EDIT : I figured out that there was some other problem in my code, and corrected it.After that all the answer I had to this question works.Thank you for helping and teaching me new things.
This will do the trick:
var q =
from item in kayitlar3
group item by item.DOMAINNAME into g
select g.OrderByDescending(i => i.KALANGUN).First();
You can also try this:
var q =
from row in islemDetayKayitListesi
group row by row.GetSetDomainName into g
let highest = g.OrderByDescending(r => r.GetSetKalanGun).First()
select new
{
KAYITNO = highest.GetSetKayitNo,
DOMAINNAME = g.Key,
KALANGUN = highest.GetSetKalanGun
};
Note that this would yield the same results. If it doesn't, there is a problem with your code that we can't see by looking at the information that you posted.
You could use:
var kayitlar3 =
islemDetayKayitListesi.
Select(rows =>
new
{
KAYITNO = rows.GetSetKayitNo,
HESAPADI = rows.GetSetHesapAdi,
URUNNO = rows.GetSetUrunNo,
URUNADI = rows.GetSetUrunAdi,
URUNMIKTAR = rows.GetSetUrunMiktar,
ISLEMTARIHI = rows.GetSetIslemTarihi,
HIZMETDURUMU = rows.GetSetHizmetDurumu,
TOPLAMTUTAR = rows.GetSetToplamTutar,
HIZMETBASLANGICTARIHI = rows.GetSetHizmetBaslangicTarihi,
HIZMETBITISTARIHI = rows.GetSetHizmetBitisTarihi,
KALANGUN = rows.GetSetKalanGun,
DOMAINNAME = rows.GetSetDomainName,
SIPARISDURUMU = rows.GetSetSiparisDurumu
}).
GroupBy(a =>
//To ignore case and trailing/leading whitespace
a.DOMAINNAME.ToUpper().Trim()).
Select(g =>
g.OrderByDescending(a => a.KALANGUN).FirstOrDefault()).
AsQueryable();
EDIT:
So using this code:
List<Thing> islemDetayKayitListesi = new List<Thing>();
Thing a = new Thing() { GetSetDomainName = "abc.com", GetSetKayitNo = 1,
GetSetKalanGun = 40 };
Thing b = new Thing() { GetSetDomainName = "abc.com", GetSetKayitNo = 2,
GetSetKalanGun = 300 };
Thing c = new Thing() { GetSetDomainName = "xyz.com", GetSetKayitNo = 3,
GetSetKalanGun = 400 };
Thing d = new Thing() { GetSetDomainName = "123.com", GetSetKayitNo = 4,
GetSetKalanGun = 124 };
islemDetayKayitListesi.Add(a);
islemDetayKayitListesi.Add(b);
islemDetayKayitListesi.Add(c);
islemDetayKayitListesi.Add(d);
var kayitlar3 =
islemDetayKayitListesi.
Select(rows =>
new
{
KAYITNO = rows.GetSetKayitNo,
HESAPADI = rows.GetSetHesapAdi,
URUNNO = rows.GetSetUrunNo,
URUNADI = rows.GetSetUrunAdi,
URUNMIKTAR = rows.GetSetUrunMiktar,
ISLEMTARIHI = rows.GetSetIslemTarihi,
HIZMETDURUMU = rows.GetSetHizmetDurumu,
TOPLAMTUTAR = rows.GetSetToplamTutar,
HIZMETBASLANGICTARIHI = rows.GetSetHizmetBaslangicTarihi,
HIZMETBITISTARIHI = rows.GetSetHizmetBitisTarihi,
KALANGUN = rows.GetSetKalanGun,
DOMAINNAME = rows.GetSetDomainName,
SIPARISDURUMU = rows.GetSetSiparisDurumu
}).
GroupBy(anon =>
anon.DOMAINNAME).
Select(g =>
g.OrderByDescending(anon => anon.KALANGUN).First()).
AsQueryable();
kayitlar3.ToList().
ForEach(anon => Console.WriteLine("{0}, {1}, {2}",
anon.KAYITNO, anon.DOMAINNAME, anon.KALANGUN));
struct Thing
{
public int GetSetKayitNo { get; set; }
public int GetSetHesapAdi { get; set; }
public int GetSetUrunNo { get; set; }
public int GetSetUrunAdi { get; set; }
public int GetSetUrunMiktar { get; set; }
public int GetSetIslemTarihi { get; set; }
public int GetSetHizmetDurumu { get; set; }
public int GetSetToplamTutar { get; set; }
public int GetSetHizmetBaslangicTarihi { get; set; }
public int GetSetHizmetBitisTarihi { get; set; }
public int GetSetKalanGun { get; set; }
public string GetSetDomainName { get; set; }
public int GetSetSiparisDurumu { get; set; }
}
I get the expected output:
2, abc.com, 300
3, xyz.com, 400
4, 123.com, 124
After clarification about your desired output, this will return the row with the top KALANGUN per DOMAINNAME:
var kayitlar3 = (
from rows in islemDetayKayitListesi
select new
{
KAYITNO = rows.GetSetKayitNo,
HESAPADI = rows.GetSetHesapAdi,
URUNNO = rows.GetSetUrunNo,
URUNADI = rows.GetSetUrunAdi,
URUNMIKTAR = rows.GetSetUrunMiktar,
ISLEMTARIHI = rows.GetSetIslemTarihi,
HIZMETDURUMU = rows.GetSetHizmetDurumu,
TOPLAMTUTAR = rows.GetSetToplamTutar,
HIZMETBASLANGICTARIHI = rows.GetSetHizmetBaslangicTarihi,
HIZMETBITISTARIHI = rows.GetSetHizmetBitisTarihi,
KALANGUN = rows.GetSetKalanGun
DOMAINNAME = rows.GetSetDomainName,
SIPARISDURUMU = rows.GetSetSiparisDurumu
})
.GroupBy(rr => rr.DOMAINNAME)
.SelectMany(gg => gg.OrderByDescending(rr => rr.KALANGUN).First());
Try
from rows in islemDetayKayitListesi
group rows by new { rows.GetSetDomainName} into results
let MaxKALANGUN = results.Max(i=>i.KALANGUN)
select new
{
KAYITNO = results.First(i=>i.KALANGUN== MaxKALANGUN).GetSetKayitNo
DOMAINNAME = results.Key.GetSetDomainName ,
KALANGUN = MaxKALANGUN
}
If you want the complete class, try
from rows in islemDetayKayitListesi
group rows by new { rows.GetSetDomainName} into results
let MaxKALANGUN = results.Max(i=>i.KALANGUN)
select results.First(i=>i.KALANGUN== MaxKALANGUN)

Categories