3

我有IEnumerable<RuleSelection>这些属性:

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

RuleIdinRuleSelection不是唯一的。

我可以编写一个 linq 查询来将这些规范化为IEnumerable<Rule>

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

Rule.RuleId将是唯一的,并且属性Criteria将分别CriteriaSource包括所有的CriteriaId' 和CriteriaSourceId' RuleId

4

3 回答 3

10

听起来你想要这样的东西:

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(),
                              });
于 2013-03-06T22:43:36.577 回答
0

使用我的 FullOuterGroupJoin 扩展方法

你可以:

theRules.FullOuterGroupJoin(theRules,
        r => r.RuleId,
        r => r.RuleId,
        (crit, critSource, id) => new Rule { 
            RuleId = id, 
            Criteria = crit
                .Where(r => r.CriteriaId.HasValue)
                .Select(r => r.CriteriaId.Value),
            CriteriaSource = critSource
                .Where(r => r.CriteriaSourceId.HasValue)
                .Select(r => r.CriteriaSourceId.Value),
        }
    );
于 2013-03-06T22:53:11.760 回答
0

要写这个:

var rules =
    from sel in selections
    group sel by sel.RuleId into rg
    select new Rule {
        RuleId = rg.Key,
        Criteria = rg.Select(r => r.CriteriaId).FilterValues(),
        CriteriaSource = rg.Select(r => r.CriteriaSourceId).FilterValues(),
    };

我创建了以下FilterValues扩展(以消除重复):

public static IEnumerable<T> FilterValues<T>(
    this IEnumerable<T?> items)
    where T : struct
{
    // omitting argument validation
    return 
        from item in items 
        where item.HasValue
        select item.Value;
}

我着手提供基本上是 JonSkeet 答案的纯查询语法版本。为了消除属性分配的重复,我放弃了这一点,并最终采用了这种组合扩展和查询语法的方法。

于 2013-03-07T03:45:28.133 回答