【问题标题】:Using linq with if-query将 linq 与 if-query 一起使用
【发布时间】:2017-01-08 17:20:55
【问题描述】:

我有以下代码将 FileInfos 列表分组:

            var group_infos =
            from info in fileInfos
            where info.Length < 1024 * 1024
            group info by info.Name into g
            where g.Count() > 1
            orderby g.Count() descending, g.Key
            select g;

现在我想对组子句进行 if 查询。也许在字符串的帮助下

string groupClausel = "Name";

或枚举:

    public enum FilterMethod
    {
        Directory,
        CreationTime,
        DirectoryName,
        Extension,
        Length, 
        Name
    }

但我不知道如何检查组子句中的字符串或枚举。我知道有这样的语法

    group info by (groupClausel == "Extension" ? info.Extension : info.Name) into g

但这让我只选择两个属性...

你们有想法吗?

【问题讨论】:

  • 所以你想要更多的条件?
  • 不,我想检查用户想要的组方法。如果他想按名称分组:按名称分组。如果他想按长度分组:按长度分组。如果他想分组.......

标签: c# winforms fileinfo system.io.fileinfo


【解决方案1】:

您可以在这里使用方法语法而不是查询语法,我认为它会更易于维护和阅读。

例如,您可以创建一个方法,该方法通过键选择器函数返回分组:

private Func<FileInfo, object> GetGroupByKeySelector(FilterMethod filterMethod)
{
    Func<FileInfo, object> keySelector = null;
    switch (filterMethod)
    {
        case FilterMethod.Directory:
            keySelector = f => f.Directory;
            break;

        case FilterMethod.CreationTime:
            keySelector = f => f.CreationTime;
            break;

        case FilterMethod.DirectoryName:
            keySelector = f => f.DirectoryName;
            break;

        case FilterMethod.Extension:
            keySelector = f => f.Extension;
            break;

        case FilterMethod.Length:
            keySelector = f => f.Extension;
            break;

        default:
            keySelector = f => f.Name;
            break;
    }
    return keySelector;
}

然后你就可以按照下面的描述使用它了:

FilterMethod prop = FilterMethod.CreationTime;
var groupInfos = fileInfos
    .Where(f => f.Length < 1024 * 1024)
    .GroupBy(GetGroupByKeySelector(prop))
    .Where(g => g.Count() > 1)
    .OrderByDescending(g => g.Count())
    .OrderBy(g => g.Key)
    .Select(g => g);

此外,如果您的枚举反映了 FileInfo 属性名称,您可以使用 System.Net.Reflection 库来避免在 GetGroupByKeySelector 方法中使用 switch-case

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-27
    • 2010-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多