Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Normalize objects using linq

Tags:

c#

linq

I have an IEnumerable<RuleSelection> with these properties:

public class RuleSelection{
  public int RuleId { get; set;}
  public int? CriteriaId { get; set; }
  public int? CriteriaSourceId{ get; set; }
}

RuleId in RuleSelection is not unique.

Can I write a linq query to normalize these into IEnumerable<Rule> which would be:

public class Rule{
  public int RuleId { get; set; }
  public IEnumerable<int> Criteria { get; set; }
  public IEnumerable<int> CriteriaSource { get; set; }
}

Rule.RuleId would be unique and the properties Criteria and CriteriaSource would include all the CriteriaId's and CriteriaSourceId's for the RuleId respectively.

like image 493
adam0101 Avatar asked Apr 20 '26 00:04

adam0101


1 Answers

It sounds like you want something like:

var rules = selections.GroupBy(rs => rs.RuleId)
                      .Select(g => new Rule {
                                  RuleId = g.Key,
                                  Criteria = g.Select(rs => rs.CriteriaId)
                                              .Where(c => c != null)
                                              .Select(c => c.Value)
                                              .ToList(),
                                  CriteriaSource = g.Select(rs => rs.CriteriaSourceId)
                                                    .Where(c => c != null)
                                                    .Select(c => c.Value)
                                                    .ToList(),
                              });
like image 172
Jon Skeet Avatar answered Apr 22 '26 13:04

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!