按字段名称对项目排序

时间:2019-06-25 14:11:39

标签: c# .net linq

我想对许多领域进行一般性区分。 现在,我必须为每个字段写这个:

  if (cFieldName == "cEVEN_DAL")
  {
    eventLOGS_DistinctField = eventLogs.DistinctBy(x => x.cEVEN_DAL);
  }

我想做的事情是这样的:

eventLOGS_DistinctField = eventLogs.DistinctBy(myFieldName);

可以这样做吗?

2 个答案:

答案 0 :(得分:2)

您可以使用Linq API生成表达式x => x.cEVEN_DAL

// because you said in comments that all fields are string I'm using Func<T, string> here
public static Expression<Func<T, string>> Create<T>(string fieldName)
{
    var parameter = Expression.Parameter(typeof(T), "p");
    var property = Expression.PropertyOrField(parameter, fieldName);
    return Expression.Lambda<Func<T, string>>(property, parameter);
}

如果您是usinq MoreLinq,则需要编译以下表达式:

var lambda = Create< TypeOfEventLogItem  >("cEVEN_DAL");
var func = lambda.Compile();
var result = eventLogs.DistinctBy(func);

答案 1 :(得分:1)

这种方式:

class Program
{
    static void Main(string[] args)
    {
        List<Test> tests = new List<Test>() //Example objects
        {
            new Test
            {
                A = 1,
                B = 2,
                C = 3,
            },
            new Test
            {
                A = 2,
                B = 2,
                C = 3,
            },
            new Test
            {
                A = 3,
                B = 2,
                C = 3,
            },
            new Test
            {
                A = 1,
                B = 1,
                C = 3,
            },
            new Test
            {
                A = 1,
                B = 2,
                C = 3,
            },
            new Test
            {
                A = 1,
                B = 3,
                C = 3,
            },
            new Test
            {
                A = 1,
                B = 2,
                C = 1,
            },
            new Test
            {
                A = 1,
                B = 2,
                C = 2,
            },
            new Test
            {
                A = 1,
                B = 2,
                C = 3,
            }
        };
        List<Test> results = DistinctBy(tests, "A"); //Use of DistinctBy
    }

    private static List<T> DistinctBy<T>(List<T> objs, string propertyName)
    {
        Type type = typeof(T);
        PropertyInfo property = type.GetProperty(propertyName);
        return objs.GroupBy(x => property.GetValue(x)).Select(x => x.First()).ToList();
    }
}

public class Test
{
    public int A { get; set; }
    public int B { get; set; }
    public int C { get; set; }
}