为了账号安全,请及时绑定邮箱和手机立即绑定

寻找模式.

寻找模式.

C#
眼眸繁星 2023-09-24 11:18:15
我需要在列表中搜索是否存在某种模式。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::writeror Resource:resource1::writeror Resource:resource1:resource2::writer ie 基于 : 分割 x 并将 y 附加到分割 x 的组合
查看完整描述

3 回答

?
烙印99

TA贡献1829条经验 获得超13个赞

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

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

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

例如:如果您有类似 A::ZA::YA:B::XA: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 中以查看每个步骤。


查看完整回答
反对 回复 2023-09-24
?
守着一只汪

TA贡献1872条经验 获得超3个赞

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


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();


查看完整回答
反对 回复 2023-09-24
?
米琪卡哇伊

TA贡献1998条经验 获得超6个赞

      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;


查看完整回答
反对 回复 2023-09-24
  • 3 回答
  • 0 关注
  • 73 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信