public AddressGroupsViewModel GetSearchResults(bool address1, bool address2, bool city, bool state, bool country, bool postalcode)
{
var result = from t in tableName
group t by new {
FieldA = (address1 ? "" : t.Address1),
FieldB = (address2 ? "" : t.Address2),
FieldC = (city ? "" : t.City),
FieldD = (state ? "" : t.State),
FieldE = (country ? "" : t.Country),
FieldF = (postalcode ? "" : t.PostalCode)
} into g
select g;
......
}
GroupBy on Multiple Properties Based on Parameters
Question
I have a table full of addresses. My goal is to find people who have similar addresses, and group them together. I can, of course, do :
var groups = addresses.GroupBy(a => a.FullAddress);
which is fine. But the user is offered the option to select the address properties they want to be applied in the GroupBy. For Example:
//user selected postalCode & state
var groups = addresses.GroupBy(a => new { a.PostalCode, a.State });
There are 6 booleans that the user can incorporate into their search in total. Is there a simple way via LINQ to approach this problem? I'm sure I can hammer out some if statements if not, but I imagined there was a more elegant solution, and I was unable to find any similar questions.
This is in an ASP.NET MVC project, as part of a service that builds up an AddressGroupsViewModel
using the Entity Framework for a reporting page.
public AddressGroupsViewModel GetSearchResults(bool address1, bool address2, bool city, bool state, bool country, bool postalcode)
{
}
SOLUTION
Given the accepted answer (which was nearly what I needed), I created this query that satisfies my requirements :
var groups = dbContext
.GroupBy(t => new
{
Address1 = (address1 ? t.AddressLine1 : ""),
Address2 = (address2 ? t.AddressLine2 : ""),
City = (city ? t.City : ""),
State = (state ? t.State : ""),
Country = (country ? t.Country : ""),
PostalCode = (postalcode ? t.PostalCode : "")
});
Solution