c# - 在 List<T> 中查找项目

标签 c# class list .net-4.0 ignore-case

我有以下示例:

public class Commands
{
    public int ID { get; set; }
    public List<string> Alias { get; set; }
}

public class UserAccess
{
    public int AccessID { get; set; }
    // other stuff not needed for the question
    public List<Commands> AllowedCommands { get; set; }
}

现在我想在 UserAccess 上实现一种返回命令 ID 的方法,如果在列表中没有找到别名,则返回 NULL,请看下面我所说的一个肮脏的例子 HasCommand :

public class UserAccess
{
    public ID { get; set; }
    // other stuff not needed for the question
    public List<Commands> AllowedCommands { get; set; }

    public Commands HasCommand(string cmd)
    {
        foreach (Commands item in this.AllowedCommands)
        {
            if (item.Alias.Find(x => string.Equals(x, cmd, StringComparison.OrdinalIgnoreCase)) != null)
                return item;
        }
        return null;
    }
}
  • 我的问题是运行或实现 HasCommand 方法的最有效方式是什么?

  • 或者是否有更好的方法将其实现到 UserAccess 中?

最佳答案

可以缩短一点

public Commands HasCommand(string cmd)
{
    return AllowedCommands.FirstOrDefault(c => c.Alias.Contains(cmd, StringComparer.OrdinalIgnoreCase));

}

但这几乎是一回事。

关于c# - 在 List<T> 中查找项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7651801/

相关文章:

python - 在python中读取多层csv文件

C# 使用 Except 比较列表

python - 如何将列表类型更改为str?

c# - 如何监听Textfile并在文本框中连续输出内容?

css - 添加带有 css 绑定(bind)的动态类

c++ - 在类中定义输出文件流

c++ - 数组与结构 C++

c# - 反序列化List Json C#中的List

c# - Jquery 在 selenium 中找不到元素

c# - AutoResetEvent - 两次快速调用不能保证线程释放 - 为什么?