查找两个列表中包含的子字符串项

时间:2019-01-11 08:38:48

标签: c# linq

我有两个列表:

var files = new List<string> {"ax_11118.txt", "ax_422226.txt", "ax_4346436.txt", "678678678.txt"};
var codes = new List<string> { "1111", "1234", "5555" };

我需要在包含以下格式的文件中找到项目:“ ax_code”。在这种情况下,结果应为:{ "ax_11118.txt" }

我知道如何使用foreach来做到这一点,但是我在想是否有更清洁的方法。

4 个答案:

答案 0 :(得分:4)

如果您只想检查代码,则:

files.Where(file => codes.Any(file.Contains));

如果是ax_code:

files.Where(file => codes.Any(code => file.Contains($"ax_{code}")));

答案 1 :(得分:2)

使用StartsWith方法

var files = new List<string> { "ax_11118.txt", "ax_422226.txt", "ax_4346436.txt", "678678678.txt" };
var codes = new List<string> { "1111", "1234", "5555" };
files.Where(file => codes.Exists(code => file.StartsWith($"ax_{code}"))).ToList();

答案 2 :(得分:0)

您可以使用此:

{...; print}

答案 3 :(得分:0)

另一个选择是使用Join和Custom EqualityComparer

var results = files.Join(codes, f=> f, c => c, (f,c) => f,new CustomEqualityComparer());

CustomEqualityComparer定义为

class CustomEqualityComparer : IEqualityComparer<string>
{
    public bool Equals(string left, string right)
    {
        return right.StartsWith($"ax_{left}");
    }

    public int GetHashCode(string str)
    {
        return 0;
    }
}
相关问题