微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 除了LINQ中的LIKE条件外

我有一个包含文件路径的字符串列表.
List<string> allFilesWithPathList = new List<string>();

allFilesWithPathList.Add(@"G:\Test\A.sql");
allFilesWithPathList.Add(@"G:\Test\B.sql");
allFilesWithPathList.Add(@"G:\Test\C.sql");

return allFilesWithPathList;

我有一个列表,其中包含一个文件的子集 – 但它只有文件名;不是路径.

List<string> excludeList = new List<string>();
excludeList.Add("B.sql");

现在我需要从excludeList中不存在的allFilesWithPathList获取文件.目前,我正在使用EXCEPT,在创建另一个仅包含文件名的列表后,执行以下操作.

List<string> allFileNamesOnlyList = new List<string>();
foreach (string fileNameWithPath in allFilesWithPathList)
{
    //Remove path and get only file name
    int pos = fileNameWithPath.LastIndexOf(@"\") + 1;
    string value = fileNameWithPath.Substring(pos,fileNameWithPath.Length - pos);
    allFileNamesOnlyList.Add(value);
}

//EXCEPT logic
List<string> eligibleListToProcess = allFileNamesOnlyList.Except(excludeList).ToList();

LINQ中最好的方式是让这个逻辑工作,而不需要引入如上所述的其他列表?

注意:我正在使用.Net 4.5

完整代码

class Program
{
    static void Main(string[] args)
    {
        List<string> allFilesWithPathList = GetAllFilesWithPath();

        List<string> excludeList = new List<string>();
        excludeList.Add("B.sql");

        List<string> allFileNamesOnlyList = new List<string>();
        foreach (string fileNameWithPath in allFilesWithPathList)
        {
            //Remove path and get only file name
            int pos = fileNameWithPath.LastIndexOf(@"\") + 1;
            string value = fileNameWithPath.Substring(pos,fileNameWithPath.Length - pos);
            allFileNamesOnlyList.Add(value);
        }

        //EXCEPT logic
        List<string> eligibleListToProcess = allFileNamesOnlyList.Except(excludeList).ToList();

        //Print all eligible files
        foreach (string s in eligibleListToProcess)
        {
            Console.WriteLine(s);
        }
        Console.ReadLine();
    }

    public static List<string> GetAllFilesWithPath()
    {
        List<string> allFilesWithPathList = new List<string>();

        allFilesWithPathList.Add(@"G:\Test\A.sql");
        allFilesWithPathList.Add(@"G:\Test\B.sql");
        allFilesWithPathList.Add(@"G:\Test\C.sql");

        return allFilesWithPathList;
    }
}

解决方法

这应该工作
allFilesWithPathList.Where(x => !excludeList.Any(y => x.EndsWith(y)))

原文地址:/csharp/92247.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐