搜索模式

时间:2019-08-26 11:05:39

标签: c# string linq .net-core

我需要搜索列表中是否存在某种模式。

var result=roles.Where(z=>z.Contains(x) && z.Contains(y)).ToList();

string x = "Resource:resource1:resource2";
string y = "writer";
List<string> roles=new List<string>{"Resource::reader","Resource:resource1::Deleter","Resource:resource1::writer"};

我需要查找角色列表中是否存在任何值,例如:

Resource::writerResource:resource1::writer或     Resource:resource1:resource2::writer 即基于x分割x,并将y附加到分割x的组合中

3 个答案:

答案 0 :(得分:1)

如果我对您的问题的理解是正确的:

您有一个列表,其中可以包含您为角色命名的任何内容。这些角色的格式为A :: B或A:B :: C或A:B:C :: D等...

您想要实现的是找到x的任何“路径”或路径组合是否可以赋予y角色?

例如:如果您具有A :: Z A :: Y A:B :: X A:B:C :: X

您有x,即A:B:C

您有y,即X

您要检查的是列表中是否有A :: X

如果不这样做,则要检查列表中的A:B :: X,

如果仍然不这样做,则将查找A:B:C :: X

再次,如果我是对的,您可以考虑这样的事情:

        String path = "A:B:C";
        String roleNeeded = "X";
        List<String> roles = new List<string>() { "A::Z", "A::Y", "A:B::X" };

        List<String> pathStep = new List<string>();
        pathStep = path.Split(':').ToList();

        String lookupPath = String.Empty;
        String result = String.Empty;
        pathStep.ForEach( s =>
        {
            lookupPath += s;
            if (roles.Contains(lookupPath + "::" + roleNeeded))
            {
                result = lookupPath + "::" + roleNeeded;
            }
            lookupPath += ":";
        });

        if (result != String.Empty)
        {
            // result is Good_Path::Role
        }

通过这种方式,您开始将路径X拆分为列表,然后将其汇总到foreach中以查看每个步骤。

答案 1 :(得分:0)

您应该考虑使用正则表达式。试试吧,

string x = "Resource:resource1:resource2";
string y = "writer";
List<string> roles;
List<string> words   = new List<string> { x, y };
// We are using escape to search for multiple strings.
string       pattern = string.Join("|", words.Select(w => Regex.Escape(w)));
Regex        regex   = new Regex(pattern, RegexOptions.IgnoreCase);

// You got matched results...
List<string> matchedResults = roles.Where(regex.IsMatch).ToList();

答案 2 :(得分:0)

        string x = "Resource:resource1:resource2";
        string y = "writer";
        List<string> roles = new List<string>
        {
            "Resource::writer",
            "Resource:resource1:resource2::writer"
        };

        var records = x.Split(':').Select((word, index) => new { word, index });

        var result =
            from record in records 
            let words = $"{string.Join(":", records.Take(record.index + 1).Select(r => r.word))}::{y}"
            join role in roles on words equals role
            select words;