Order by date date with linq and entity framework - c#

I have this code:
List<jogo> lista_realizados = tt.jogo.Where(c => c.activo == 1 &&
c.progresso == 2 &&
c.id_torneio == torn.id_torneio)
.ToList();
var q1 = lista_realizados.Select(c => new { resultado = c.resultado,
id = c.id_jogo,
torneio = c.torneios.nome,
Data = c.data,
Hora = c.hora,
jogador = c.jogador.Nome_jogador,
jogador2 = c.jogador2.Nome_jogador,
Clube = c.clubeparceiro.nome,
agendadopor = c.alterado_por})
.OrderByDescending(p => p.Data.Value.Month )
.ToList();
gvListaJogos.DataSource = q1;
gvListaJogos.DataBind();
I get the list and then I try to order the list by the field Data - it is defined as a Date in sql. And in the code appeared as a ?Datetime.
But it seems that the list is being ordered by string and not by the date.

I'm guessing that gvListaJogos is a ListBox.
Make sure the Sorted property of the ListBox is set to false.

Related

where to put orderby in linq statement

Here is my code and i want to order by via date_added column. i tried all the possibilities but still the date_added column sorted via month instead of a year. Please guide where i need to put orderby statement.further the date_added return result in string datatype.
{
var records = (from r in db2.documents
select new
{
r.show_in_portal,
r.buyer_id,
r.advertiser_id,
r.contract_id,
r.campaign_id,
date_added = Dates.FormatDateToExt(r.date_added),
id = r.document_id,
name = r.filename,
location = r.filename,
r.publisher_id,
affiliate_id = (r.contract != null ? r.contract.publisher_id : -1),
document_type = r.document_type.type_name
});
if (campaign_id > 0)
records = records.Where(v => v.campaign_id == campaign_id);
//if (creativeid > 0)
// records = records.Where(v => v.id == creativeid);
if (affid > 0)
records = records.Where(v => v.publisher_id == affid);
if (contid > 0)
records = records.Where(v => v.contract_id == contid);
if (advertiserid > 0)
records = records.Where(v => v.advertiser_id == advertiserid);
if (buyerid > 0)
records = records.Where(v => v.buyer_id == buyerid);
GridOut(context, records.ToArray());
}
public static string FormatDateToExt(DateTime? input)
{
return FormatDateToExt(input, 0);
}
public static string FormatDateToExt(DateTime? input, int time_offset = 0)
{
return input != null ? input.Value.AddHours(-1 * time_offset).ToString("MM/dd/yyy h:mm:ss tt") : "";
}
The result of your query is a sequence of some anonymous type. Date_Added is one of the properties of this anonymous type, so after you created your query you can order by Date_Added.
The type of Date_Added is the returned type of Dates.FormatDateToExt(...). Alas you forgot to inform us about this type. Is it a DateTime? Is it a string? If you order by this type do you get the sorting order that you want?
If so, just add the OrderBy at the end:
var records = db2.documents.Select(document => new
{
Id = document.document_id,
Portal = document.Show,
BuyerId = document.buyer_id,
AdvertiserId = document.advertiser_id,
...
DateAdded = Dates.FormatDateToExt(document.date_added),
});
if (campaign_id > 0)
records = records.Where(record => record.campaign_id == campaign_id);
if (affid > 0)
records = records.Where(record => record.publisher_id == affid);
... // etc. other ifs and other wheres
records = records.OrderBy(record => record.DateAdded);
It is a good thing to do the Sorting at the end, because this means that you will have to sort fewer records. All records that don't pass all Wheres, won't have to be sorted.
Finally a small hint: did you see, that if you use proper identifiers, that your queries will be easier to read? It is good practice to use plural nouns for collections of items, and singular nouns for elements of the collection:
var novels = dbContext.Books.Where(book => book.Type == BookType.Novel)
Consider making your dates uniform by using ISO 8601 ones (convert them on the fly in your Linq query), as they're made to be sortable.
You can put the orderby clause after the from.
Read:
https://www.c-sharpcorner.com/UploadFile/mahesh/working-with-datetime-using-C-Sharp/
https://dev.to/adnauseum/sorting-iso-8601-timestamps-5am2

Improving speed of method after adding value from different table aspn.net

I've got two tables: Index and Codes
when one condition is true, I need to check whether the Index is still valid and for that I need to get EndDate of the code which is in Codes table (as I've got only id of code in Index table)
This is how I do that:
1) First I get all Codes that have ended already (approx 3k+ items)
var goods = _context.Codes.Select(a =>
new Codes
{
Loid = a.Loid,
Pid = a.Pid,
Code = a.Code,
Startdate = a.Startdate,
Enddate = a.Enddate
})
.Where(x => x.Enddate < DateTime.Now)
.ToList();
then I'm taking my Index and adding values there as well as CodeEnd from Codes list above:
query = _context.VpAbcIndex
.AsNoTracking()
.Select(e => new VpAbcIndex
{
Id = e.Id,
ParentName = e.ParentName ?? "!",
ParentEndDate = e.ParentEndDate,
ParentStartDate = e.ParentStartDate,
ParentCode = e.ParentCode,
ParentNote = e.ParentNote ?? "",
ParentStatus = e.ParentStatus,
ChildName = e.ChildName ?? "!",
ChildId = e.ChildId,
ChildEndDate = e.ChildEndDate,
ChildStartDate = e.ChildStartDate,
CodeEnd = (filter.Level == 0) ? goods
.FirstOrDefault( x => x.Code == e.ParentCode).Enddate :
(filter.Level == 1) ? goods
.FirstOrDefault(x => x.Code == e.ChildCode).Enddate :
(filter.Level == 2) ?
goods
.FirstOrDefault(x => x.Code == e.GrandChildCode).Enddate : null
})
;
}
That's approx 10k items. It doesn't seem that much however it takes quite a long time for them to appear in my browser. Am I doing something wrong? Is there a faster way to join these values?

how to Filter one list based on another lists field

I am fetching data from database from separater tables and storing in separate variables.
this is first list
var res = (from v in context.MasterValues
join c in context.MasterCategories on v.Category_Id equals c.Id
where c.Model_Key == (int)model && c.Name == tableName && v.Version_Id == version && v.Active == "Y" && c.Name.Equals("FXRates")
select new
{
Id = v.Id,
VersionId = v.Version_Id,
Text1 = v.Text1,
}).ToList();
This is second list
var fxview = context.MasterFXRates.Select
(x => new
{
Currency_code = x.Currency_code,
Rate = x.Rate,
Effective_dt = x.Effective_dt
}
).ToList();
So now How to filter Data from my second list fxview based on data from my first list ?
i.e.
i need to filter data where Currency_code's data of list2 matches with Text1 of List1 where effective_dt(datetime column) is maximum/Latest date
For Example if second lists data has
ABC , 100 , 2010-10-10
ABC , 120 , 2014-12-12
DEF ,700 , 2013-08-02
DEF ,500 ,2015-06-06
And List 1(res) has following data
1 , 1 , ABC
2 , 1 , DEF
So after filtering my final list must have following output
ABC ,120 (Since 2014-12-12 is latest date , the corresponding value is fetched and duplicate value (ABC,100) should be filtered.)
2.DEF ,500 (Since 2015-06-06 is latest date , the corresponding value is fetched and duplicate value (DEF,&00) should be filtered.)
var result = from masterFxRate in masterFxRates
join masterValue in masterValues on masterFxRate.Currency_code equals masterValue.Text1
group masterFxRate by
new
{
masterFxRate.Currency_code
} into groupedRates
select new
{
groupedRates.Key.Currency_code,
Rate = groupedRates.FirstOrDefault(g => g.Effective_dt != null
&& g.Effective_dt == groupedRates.Max(c => c.Effective_dt)).Rate
};
foreach (var item in result)
{
Console.WriteLine("{0} : {1} ", item.Currency_code, item.Rate);
}
fxView = fxView.OrderByDescending(x => x.effectiveDate).ToList();
var result = new List();
res.ForEach((x) => result.Add(fxView.First(y => x.text1 == y.currency_code)));
If effectiveDate is already a DateTime this should work otherwise convert it to a DateTime
var fxview = context.MasterFXRates.Select
(x => new
{
Currency_code = x.Currency_code,
Rate = x.Rate,
Effective_dt = Convert.ToDateTime(x.Effective_dt)
}
).ToList();

convert sql to linq with two tables

select ind.desc,ind.number
from int_goals_df idd, goals_df ind
where idd.dld_number = 123456
and ind.number = idd.ind_number
and ind.categorie = 2
order by follownumber
I'm having a hard time translating this to linq since it is using two tables.
I've currently solved this now imperatively with a foreach loop but not happy with it..
I'm trying to get a list of goals_df that matches with a list of int_goals_df.
Any tips would be greatly appreciated ! Thank you !
EDIT - here is the code I'm using:
//get current GoalDefinitions by selected Goal
var currentGoalDefinition = MyAppAppContext.MyAppAppContextInstance.MyAppContext.GoalDefinitions.FirstOrDefault(
d => d.DLD_GoalDFID == interv.Goal.DLD_GoalenDFID);
// get current intervGoalDefinitions by GoalDefinition
var currentintervGoalDefinitions = MyAppAppContext.MyAppAppContextInstance.MyAppContext.intervGoalDefinitions.Where(
idd => idd.DLD_GoalDFID == currentGoalDefinition.DLD_GoalDFID).OrderBy(idd => idd.IDD_VolgNummer);
intervDefinitionCollection = new ObservableCollection<intervDefinition>(MyAppAppContext.MyAppAppContextInstance.MyAppContext.intervDefinitions.Where(i => i.IND_Categorie == intCategorie));
// filter intervGoalDefinitions by intervDefinitions
var intervDefinitionCollectionTemp = new ObservableCollection<intervDefinition>();
foreach (var currentintervGoalDefinity in currentintervGoalDefinitions)
{
var foundintervGoalDefinitySorted = intervDefinitionCollection.FirstOrDefault(
i => i.IND_intervDFID == currentintervGoalDefinity.IND_intervDFID);
if (foundintervGoalDefinitySorted != null)
intervDefinitionCollectionTemp.Add(foundintervGoalDefinitySorted);
}
intervDefinitionCollection = intervDefinitionCollectionTemp;
assuming NHibernate as ORM and int_goal is a subclass of goal
var results = from idd in session.Query<IntGoals>()
where idd.DlDNumber = 123456 && idd.Category.Id == 2
orderby idd.FollowNumber
select new { idd.Description, idd.Number };
context.int_goals_df.Join(context.goals_df, x => x.ind_number, x => x.number,
(x, y) => new
{
idd = x,
ind = y
})
.Where(x => x.idd.dld_number = 123456 && x.ind.categorie = 2)
.OrderBy(x => x.idd.follownumber)
.Select(x => new
{
x.ind.desc,
x.ind.number
});
quick go - think you need the join
var results = from idd in session.Query<int_goals_df>()
join ind in session.Query<goals_df>()
on idd.ind_number equals ind.ind_number
where idd.DlDNumber = 123456 && idd.Category.Id == 2
orderby idd.FollowNumber
select new { idd.Description, idd.Number };
I tend to use the sql syntax without implicit joins
/*Fields*/
SELECT ind.desc, ind.number
/*Tables*/
FROM int_goals_df idd
INNER JOIN goals_df ind
ON ind.number = idd.ind_number
/*Conditions*/
WHERE idd.dld_number = 123456
AND ind.categorie = 2
/*Order/Grouping*/
ORDER BY follownumber
You can see from Chris's answer this translates more easily to linq.

Issue with LINQ group by with count

I'm trying to run the following query but for some reason MemberTransactionCount and NonMemberTransactionCount are coming back as the exact same values. It seems that the .Where() clauses aren't working as we'd expect them to.
Hoping someone can point out where I might be going wrong.
from trans in transactions
orderby trans.TransactionDate.Year , trans.TransactionDate.Month
group trans by new {trans.TransactionDate.Year, trans.TransactionDate.Month}
into grp
select new MemberTransactions
{
Month = string.Format("{0}/{1}", grp.Key.Month, grp.Key.Year),
MemberTransactionCount =
grp.Where(x => x.Account.Id != Guid.Empty || x.CardNumber != null)
.Sum(x => x.AmountSpent),
NonMemberTransactionCount =
grp.Where(x => x.Account.Id == Guid.Empty && x.CardNumber == null)
.Sum(x => x.AmountSpent)
}
EDIT
I've verified in the database that the results are not what they should be. It seems to be adding everything together and not taking into account the Account criteria that we're looking at.
I ended up solving this with two separate queries. It's not exactly as I wanted, but it does the job and seems to just as quick as I would have hoped.
var memberTrans = from trans in transactions
where trans.Account != null
|| trans.CardNumber != null
orderby trans.TransactionDate.Month
group trans by trans.TransactionDate.Month
into grp
select new
{
Month = grp.Key,
Amount = grp.Sum(x => x.AmountSpent)
};
var nonMemberTrans = (from trans in transactions
where trans.Account == null
&& trans.CardNumber == null
group trans by trans.TransactionDate.Month
into grp
select new
{
Month = grp.Key,
Amount = grp.Sum(x => x.AmountSpent)
}).ToList();
var memberTransactions = new List<MemberTransactions>();
foreach (var trans in memberTrans)
{
var non = (from nt in nonMemberTrans
where nt.Month == trans.Month
select nt).FirstOrDefault();
var date = new DateTime(2012, trans.Month, 1);
memberTransactions.Add(new MemberTransactions
{
Month = date.ToString("MMM"),
MemberTransactionCount = trans.Amount,
NonMemberTransactionCount = non != null ? non.Amount : 0.00m
});
}
I think the main problem here is that you doubt the result, though it might be correct.
Add another property for verification:
TotalAmount = grp.Sum(x => x.AmountSpent)

Categories

Resources