LINQ grouping multiple fields only if one of the fields is a specific value
The GroupBy
returns an anonymous type with 2 fields. The values inside the returned object can be anything. In this case they can be altered if the category is "01": myItemList.GroupBy(a=> new {a.Category, Vendor= a.Category == "01" ? null : a.Vendor})
To keep in line with your current code, the property is named Vendor, but can be any name.
In your current code:
List<MyItem> groupedItems = myItemList
.GroupBy(a => new {a.Category, Vendor = a.Category == "01" ? null : a.Vendor})
.Select(b => new MyItem
{
Vendor = b.First().Vendor,
Cost = b.Sum(c => c.Cost),
Category = b.First().Category
})
.ToList();
Or with a slight alteration, instead of the First()
value of a group, you can reuse the key (and implement the N\A
in one go)
List<MyItem> groupedItems = myItemList
.GroupBy(a=> new {a.Category, Vendor= a.Category == "01" ? "N/A" : a.Vendor})
.Select(b=> new MyItem{
Vendor = b.Key.Vendor,
Cost = b.Sum(c => c.Cost),
Category = b.Key.Category
}).ToList();
LINQ GroupBy for multiple Column
You do not need to group by multiple columns. Based on sample data you are only grouping by one field, CustomerID
.
var objCustomerBuildingMappingResult = objTicketsForTheDayInfo.TicketsForTheDay
.GroupBy(l => l.CustomerID)
.Select(grp => new CustomerBuildingMapping
{
CustomerID = grp.Key,
LeadId = long.Parse(grp.Key) + 1000,
BuildingInfo = grp.Select(l => new BuildingInfo {
BuildingID = l.BuildingID,
TicketNumber = l.Ticket,
Amount = l.Amount,
BuildingName = l.BuildingName
}).ToList(),
}).ToList();
Linq Group By multiple fields and Flatten the list
It seems to me that the only problem is that you're grouping twice. I'd expect this to work:
var query = from rating in ratings
group rating by rating.ArticleTitle into g
select new
{
Title = g.Key,
Yes = g.Count(r => r.Useful),
No = g.Count(r => !r.Useful)
};
Or not in query expression form:
var query = ratings.GroupBy(r => r.ArticleTitle,
(key, rs) => new
{
Title = key,
Yes = rs.Count(r => r.Useful),
No = rs.Count(r => !r.Useful)
});
How to GroupBy and Order by multiple fields with LINQ
If you need to filter out duplicates, try the following query:
var dtUniqueResults = dtResult.AsEnumerable()
.GroupBy(n => new
{
Id = n.Field<string>("id"),
Store = n.Field<string>("store"),
Sku = n.Field<string>("sku")
}
)
.SelectMany(g => g.Take(1)) // get from group only one record
.CopyToDataTable();
Linq Query to Group By Multiple Columns But Get Additional Properties
When you use GroupBy
in LINQ, you get an enumerable of a class which implements interface IGrouping<TKey,TElement>
- the TElement
representing the individual, and original, elements that have been grouped.
Therefore you would group like so
var grouped = myList.GroupBy(x => new {x.StoreName,x.Address1});
Which would give you an enumerable list of IGrouping<anonymous,Store>
(Assuming the original object was called Store
). The anonymous
is an anonymous object with 2 properties StoreName
and Address1
.
Now, each item in the enumerable is itself enumerable of Store
, and you can treat that exactly as you would any other enumerable - you can take the First().ID
if you wish, and you could project the whole lot back out to an enumerable if thats what you want
var result = myList.GroupBy(x => new {x.StoreName,x.Address1});
.Select(g => new {
g.Key.StoreName,
g.Key.Address1,
FirstID = g.First().ID
});
LINQ group by with multiple fields and aggregate function
In the last select statement the only parameter from the query you are accessible to is grp
; where each group is IGrouping; each group is represented by a key and an IEnumerable
which is in your case : IEnumerable<a>
. Having said that; you can replace the line total = a.kkkk.Count()
with total = grp.SelectMany(v=> v.kkkk).Count()
OR total = grp.Sum(a => a.kkkk.Count())
to resolve the issue.
This way total
represents the summation of kkkk
counts in each a in the group.
Linq to Entities grouping on multiple fields with an Or operator
Try this:-
var query = from ord in orders
group ord by new { ord.Country, ord.PostCode } into g
select new
{
Country = g.Key.Country,
PostCode = g.Key.PostCode,
Orders = g.GroupBy(x => x.OrderId)
.GroupBy(i => i.Count() > 1 ?
new { OrderID = i.Key, Email = default(string) }
: new { OrderID = default(int), i.First().Email })
.Select(o => o.Count() == 1 ?
new { o.Key, Orders = o.First().ToList() }
: new { o.Key, Orders = o.Select(z => z.First()).ToList() })
};
Here is the complete Working Fiddle.
Linq group by with multiple columns
It seems like you need grouping on Country
name as it is repeating in the data but with different id (which is strange) in that case you need to group and select the first one :
var result1 = myRepoOutput.GroupBy(x => x.Country)
.Select(b => b.First());
Returning multiple fields with LINQ GroupBy on a datatable
Create an anonymous type to group on:
var query = ds.Tables[0].AsEnumerable()
.GroupBy(r => new
{
state = r.Field<string>("state"),
name = r.Field<string>("name"),
})
.Select(grp => new
{
name = grp.Key.name,
state = grp.Key.state,
Count = grp.Count()
})
.OrderBy(o => o.state)
.ToList();
Related Topics
Binding Objects Defined in Code-Behind
What Is the Efficiency and Performance of Linq and Lambda Expression in .Net
When Is Finally Run If You Throw an Exception from the Catch Block
Iis Wcf Service Hosting VS Windows Service
.Net, Event Every Minute (On the Minute). Is a Timer the Best Option
Multi-Tenant with Code First Ef6
Performance of Find() VS. Firstordefault()
Declaring a Variable Inside or Outside an Foreach Loop: Which Is Faster/Better
Who Should Call Dispose on Idisposable Objects When Passed into Another Object
How to Get Ip of All Hosts in Lan
Selectively Suppress Custom Obsolete Warnings
How to Data Bind a List of Strings to a Listbox in Wpf/Wp7
How to Give Read/Write Permissions to a Folder During Installation Using .Net
Is There Any Connection String Parser in C#