I have a Person object:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string Address { get; set; }
public double Height { get; set; }
public bool IsTest { get; set; }
}
Then I have a list filled with different Person objects.
I want to know is there a way to use ternary operator with GroupBy in LINQ depending on some property of object. For example:
var groupedPersons = persons.GroupBy(person => person.IsTest ?
new {
person.Name,
person.Age,
person.Address
}
: new {
person.Name,
person.Age,
person.Address,
person.Height}).ToList();
But unfortunately that doesn’t work, gives me exception
Type of conditional expression cannot be determined because there is
no implicit conversion between ‘AnonymousType#1’ and ‘AnonymousType#2’
Is this achievable at all and how?
Thanks
EDIT: Tried this, but not working.
var groupedPersons = persons.GroupBy(person => person.OnTest ?
new Person {
Address = person.Address,
Name = person.Name,
Age = person.Age }
: new Person {
Address= person.Address,
Name = person.Name,
Age = person.Age ,
Height = person.Height}).ToList();
EDIT: Got it to work, look at my answer
Ok, after trying some examples shown here I realized that this is not gonna work and I got it to work other way. Here’s an example how I did it:
So if there’s a Person with property
IsTest = falsethen it usesperson.Heightto group also.