Reputation: 3025
I have a situation where the result set is 95% the same in 3 different situations. The 5% difference depends on a given variable and thus fills in (or not) the remaining 5% of fields.
As a simple example, here is the result object that is getting returned:
public class MyResults {
public string PropertyA { get; set; }
public string PropertyB { get; set; }
public string PropertyC { get; set; }
public string PropertyD { get; set; }
public string PropertyE { get; set; }
}
Currently I have a method where I build the results I have the following:
public List<MyResults> GetMyResults(int someParameter) {
IQueryable<MyResults> query;
if (someParameter == "A") {
query = entities.Select(x => new MyResults {
PropertyA = x.PropertyA, // Common
PropertyB = x.PropertyB, // Common
PropertyC = x.PropertyC, // Different
};
} else if (someParameter == "B") {
query = entities.Select(x => new MyResults {
PropertyA = x.PropertyA, // Common
PropertyB = x.PropertyB, // Common
PropertyD = x.PropertyD, // Different
};
} else {
query = entities.Select(x => new MyResults {
PropertyA = x.PropertyA, // Common
PropertyB = x.PropertyB, // Common
PropertyE = x.PropertyE, // Different
};
}
return query.ToList();
}
This is a Desired way to do this:
public List<MyResults> GetMyResults(int someParameter) {
IQueryable<MyResults> query = entities.Select(x => new MyResults {
PropertyA = x.PropertyA, // Common
PropertyB = x.PropertyB, // Common
PropertyC = x.PropertyC, // Common
};
if (someParameter == "A") {
query = entities.Select(x => new MyResults {
PropertyC = x.PropertyC // Different
});
} else if (someParameter == "B") {
query = entities.Select(x => new MyResults {
PropertyD = x.PropertyD // Different
});
} else {
query = entities.Select(x => new MyResults {
PropertyE = x.PropertyE // Different
});
}
return query.ToList();
}
This way the consistent fields on ALL results are the same and I only need to add what is different.
Is this possible?
Upvotes: 2
Views: 1056
Reputation: 37299
You can use the ternary operator as follows:
return entities.Select(x => new MyResults {
PropertyA = x.PropertyA, // Common
PropertyB = x.PropertyB, // Common
PropertyC = someParameter == 1 ? x.PropertyC : null,
PropertyD = someParameter == 2 ? x.PropertyD : null,
PropertyE = someParameter == 3 ? x.PropertyE : null,
}).ToList();
Basically as string
's default is null
if someParameter
does not match the case for a given propertyX
the properties value will be null
. If it is, it will get the desired value
Upvotes: 3