I am working on LINQ script/lambda to pull data from objects. There is a joining table/class to connect A and B table/ object.
I have managed to pull the record but it is in the following form
List<IEnumerable<ValidationRule>>
where I want to ignore joining object and simply get List<ValidationRule>
?
public static List<ValidationRule> GetValidations(string fieldName, Dictionary<string, DataMappingPolicy> dataMappingPolicies)
{
List<ValidationRule> validationRules = new List<ValidationRule>();
var policyValidations = dataMappingPolicies.Where(_ => _.Key == fieldName).Select(_ => _.Value.PolicyValidationRules.Select(_ => _.ValidationRule)).ToList();
return validationRules;
}
DataMappingPolicy
public class DataMappingPolicy
{
public DataMappingPolicy()
{
this.PolicyValidationRules = new HashSet<PolicyValidationRule>();
}
public Guid DataMappingPolicyId { get; set; }
public ICollection<PolicyValidationRule> PolicyValidationRules { get; set; }
}
PolicyValidationRule
public class PolicyValidationRule
{
public Guid PolicyValidationRuleId { get; set; }
public Guid DataMappingPolicyId { get; set; }
public DataMappingPolicy DataMappingPolicy { get; set; }
public Guid ValidationRuleId { get; set; }
public ValidationRule ValidationRule { get; set; }
}
CodePudding user response:
Flatten the list from PolicyValidationRules
to get all ValidationRule
via .SelectMany()
.
var policyValidations = dataMappingPolicies
.Where(_ => _.Key == fieldName)
.SelectMany(_ => _.Value.PolicyValidationRules)
.Select(_ => _.ValidationRule)
.ToList();
CodePudding user response:
I have an Idea on how you can fix your problem.
public static List<ValidationRule> GetValidations(string fieldName, Dictionary<string, DataMappingPolicy> dataMappingPolicies)
{
List<ValidationRule> validationRules = new List<ValidationRule>();
var policyValidations = dataMappingPolicies.Where(_ => _.Key == fieldName).Select(_ => _.Value.PolicyValidationRules.Select(_ => _.ValidationRule));
foreach(var item in policiValidations)
{
validationRules.Add(item);
}
return validationRules;
}
First remove the the ToList()
from your code.
Then if policyValidations
is of type IEnumerable<ValidationRule>
than you should be able to iterate through the values with a foreach
statement and add each of them to the list you are trying to return.
CodePudding user response:
You can use SelectMany
which flattens queries that return lists of lists.
var policyValidations = dataMappingPolicies.Where(_ => _.Key == fieldName)
.Select(_ => _.Value)
.SelectMany(_ => _.PolicyValidationRules)
.Select(_ => _.ValidationRule))
.ToList();