我如何重构这些linq属性?

时间:2014-07-07 17:42:00

标签: c# linq refactoring

我有4个类属性,它们具有相似的签名,但具有不同的linq属性。我如何创建一个委托或其他东西来清理它?

例如:

    public IEnumerable<SelectListItem> DistinctUsers
    {
        get
        {
            var list = TraceLogs.OrderBy(x => x.Username).Select(x => x.Username).Distinct();
            return (from s in list select new SelectListItem { Value = s, Text = s }
           );
        }
    }

    public IEnumerable<SelectListItem> DistinctMethods
    {
        get
        {
            var list = TraceLogs.OrderBy(x => x.Method).Select(x => x.Method).Distinct();
            return (from s in list select new SelectListItem { Value = s, Text = s }
           );
        }
    }

1 个答案:

答案 0 :(得分:7)

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

private IEnumerable<SelectListItem> GetDistinctOrderedLogs<T>
    (Func<TraceLogs, T> extraction)
{
    return TraceLogs.OrderBy(extraction)
                    .Select(extraction)
                    .Distinct()
                    .Select(s => new SelectListItem { Value = s, Text = s });
}

然后:

public IEnumerable<SelectListItem> DistinctMethods
{
    get { return GetDistinctOrderedLogs(t => t.Method); }
}

public IEnumerable<SelectListItem> DistinctUsers
{
    get { return GetDistinctOrderedLogs(t => t.Users); }
}