I have a List of the following object :
public class Item
{
public DateTime DliveryDate { get; set; }
public String Order { get; set; }
}
How can i group this List<Item> by Date using LINQ?
I used the following query but didn't got excepted result in a group by dates Got a List object with a junk date of 0001/1/1
var r = from i in Items
group i by i.DliveryDate into s
select s;
This should return what you need:
var listdategroup = from x in psrAlertLogItems.AsEnumerable<Item>()
group x by x.DliveryDate.Date into s
select s;
Maybe your ChangeDateTime contains hour/time information , you should do
var listdategroup = from i in psrAlertLogItems
group i by i.DliveryDate.Date into s select s;
to get only the day component of your datetime
May be this can help u..
var sorted_lists = from sort in lists
group sort by sort.DateInfo into sorted
select sorted;
I'm getting the correct result..
have you tried it using the extension method
var itemsGruopedByDate = Items.GroupBy(item => item.DliveryDate ).ToList();
Just an alternative.
I hope its of any use.
Cheers.
Related
I have c# list of data returning 2 dates.
5/31/2016 4:34:41 AM
5/31/2016 4:38:08 AM
I am using lambda expression to sort them to show latest date on top. But still its showing wrong. What may be the issue.
var rowEntities =
MyOperations.GetEntitiesByDate().ToList().OrderByDescending(i=>i.JobStartTime);
public DateTime JobStartTime { get; set; }
Try
var rowEntities = MyOperations.GetEntitiesByDate().OrderByDescending(i=>i.JobStartTime).ToList();
var rowEntities = MyOperations.GetEntitiesByDate().ToList().OrderByDescending(i=>i.JobStartTime);
or
var rowEntities = (from dates in MyOperations.GetEntitiesByDate() orderby dates.jobstarttime select dates).Tolist();
or
var rowEntities = (from dates in MyOperations.GetEntitiesByDate() orderby dates.jobstarttime ascending or descending select dates).Tolist();
I´m trying to make this sql request
SELECT number, COUNT(number)
FROM Bet GROUP BY number ORDER BY COUNT(number) DESC;
Code
public static List<Apuesta> GetAllNumbers(ApplicationDbContext db)
{
List<Bet> bets = (from b in db.Bet select b.Number).Count();
return bets;
}
and i want to use it in one function using linq.
To get the result you are trying to achieve you can project your query to an anonymous type:
var bets =db.Bet.GroupBy(b=>b.Number)
.Select(g=>new {Number=g.Key, Count=g.Count()})
.OrderByDescending(e=>e.Number);
Or a DTO:
public class BetDTO
{
public int Number{get;set;}
public int Count{get;set;}
}
Then project your result using that custom class:
var bets =db.Bet.GroupBy(b=>b.Number)
.Select(g=>new BetDTO{Number=g.Key, Count=g.Count()})
.OrderByDescending(e=>e.Number)
.ToList();
In addition to #octavioccl. If you like SQL-like LINQ-expressions you can use that snippet:
var bets = from b in bets group b by b.Number into g orderby -g.Key select new { Number = g.Key, Count = g.Count() });
I have the following class
public class Group
{
public string Id { get; set; }
public string Name { get; set; }
}
and 2 lists List<string> groupRestrict and List<Group> groups
now the group list contains some groups with all fields filled in and I want to select all the restricted groups, the groupRestrict list contains just the name of the groups.
I tried some things, but for some reasons, it always returns an empty list. this as my last test:
var lst = groups.Where(j => groupRestrict.Contains(j.Name)).ToList();
Any clue what might be going wrong?
Edit: Like the comments said, this should have worked, it was the input that had some ' but now I would like to have that the groupRestrict doesn't have to be the exact name, but can use 'like' features.
current expression:
var restrictedGroups = (from gr in groupRestrict join g in groups on gr equals g.Name select g).ToList();
Try:
var lst = groups.Where(j => groupRestrict.Any(x=> j.Name.Contains(x))).ToList();
this would match all groups with names that contain one or more strings from the searchList.
Case insensitive variant would be:
var lst = groups.Where(j => groupRestrict.Any(x=> j.Name.ToLower().Contains(x.ToLower()))).ToList();
Allthough it would be better to convert the groupRestrict to lowercase prior to the query in this case and you can omit the .ToLower() call for x:
string[] lowerCaseGroupRestrict = groupRestrict.Select(x=> x.ToLower()).ToArray();
var lst = groups.Where(j => lowerCaseGroupRestrict.Any(x=> j.Name.ToLower().Contains(x))).ToList();
I am populating states DDL using the country DDL
public static IEnumerable bindcountry()
{
var countries = from c in getdata().Descendants(("country"))
orderby (string)c.Element("name")
select (string)c.Element("name");
return countries;
}
public List<string> GetStatesByCountry(string CountryName)
{
var query = from user in getdata().Descendants("country")
where user.Element("name").Value == CountryName
from t in user.Descendants("text")
select t.Value;
return query.ToList();
}
foreach (var VARIABLE in ProfileMasterDAL.bindcountry())
{
if (VARIABLE.ToString().Contains(DropDownList1.SelectedItem.Text))
{
var query = from row in ProfileMasterDAL.bindcountry()
where row.(ProfileMasterDAL.GetStatesByCountrys(DropDownList1.SelectedItem.Text))
select row;
DropDownList2.DataSource = query;
DropDownList2.DataBind();
}
}
The problem is I am unable to define WHERE clause and equals here I am getting an error:
Could not find an implementation of the query pattern for source type
'System.Collections.IEnumerable'. 'Where' not found. Consider
explicitly specifying the type of the range variable 'row'.
You say that you are trying to populate a DropDownList with the names of the States for a given Country and it looks like that logic is in your foreach loop. It also looks like your foreach loop is doing a lot of unnecessary work.
It's iterating through all the Country names when it really only needs to find one of those country names. It also then iterates again through the country names looking for the states.
You should be able to throw out that entire foreach loop and instead use this:
var query = ProfileMasterDAL.GetStatesByCountry(DropDownList1.SelectedItem.Text);
DropDownList2.DataSource = query;
DropDownList2.DataBind();
Your GetStatesByCountry method returns just the states that belong to the passed in Country name, so you should just be able to call that, get the names of just those States, and then assign them to your DropDownList.
Try changing:
public static IEnumerable bindcountry()
{
var countries = from c in getdata().Descendants(("country")) orderby (string)c.Element("name") select (string)c.Element("name");
return countries ;
}
to
public static IList<string> bindcountry()
{
var countries = from c in getdata().Descendants(("country")) orderby (string)c.Element("name") select (string)c.Element("name");
return countries.ToList() ;
}
I have an array of objects. The object has two properties a value and an index.
I use a linq to entities query with the contains keyword to bring back all results in a table that match up to value.
Now here is the issue... I want to match up the results to the object index...
what is the fastest best way to perform this. I can add properties to the object.
It is almost like I want the query results to return this:
index = 1;
value = "searchkey"
queryvalue = "query value"
From your question I think I can assume that you have the following variables defined:
Lookup[] (You look-up array)
IEnumerable<Record> (The results returned by your query)
... and the types look roughly like this:
public class Lookup
{
public int Index { get; set; }
public int Value { get; set; }
}
public class Record
{
public int Value { get; set; }
/* plus other fields */
}
Then you can solve your problem in a couple of ways.
First using an anonymous type:
var matches
= from r in records
join l in lookups on r.Value equals l.Value
group r by l.Index into grs
select new
{
Index = grs.Key,
Records = grs.ToArray(),
};
The other two just use standard LINQ GroupBy & ToLookup:
IEnumerable<IGrouping<int, Record>> matches2
= from r in records
join l in lookups on r.Value equals l.Value
group r by l.Index;
ILookup<int, Record[]> matches3
= matches2.ToLookup(m => m.Key, m => m.ToArray());
Do these solve your problem?
Just a shot in the dark as to what you need, but the LINQ extension methods can handle the index as a second paramter to the lambda functions. IE:
someCollection.Select( (x,i) => new { SomeProperty = x.Property, Index = i } );