繁体   English   中英

如何在存储带有修剪的两个字符串的差异时使用Enumerable

[英]How to use Enumerable Except in storing the difference of two strings with trimming

我目前可以使用Enumerable,除了获得两个字符串的区别。

我的目标是在检查file1Lines.Except(file2Lines)时,以两个string []的20个字符临时修剪字符串的file1Lines.Except(file2Lines) ,当它返回一个值时,我希望它再次成为完整的string []

我需要这样做,因为我想比较第一个而不是第二个中的所有字符串目录,并保存完整的行(日期时间与我的字符串示例一样)

如果我无法使用Enumerable Except实现此目的,还有其他选择吗?

这是我使用的示例字符串:

2009-07-14 04:34:14 \CMI-CreateHive{6A1C4018-979D-4291-A7DC-7AED1C75B67C}\Control Panel\Desktop

这是我的示例代码:

        string[] file1Lines = File.ReadAllLines(textfile1Path);
        string[] file2Lines = File.ReadAllLines(textfile2Path);

        // This currently only gets a non-trimmed string, but if i trim it
        // it will return the trimmed string, I want it to return the full string again
        IEnumerable<String> inFirstNotInSecond = file1Lines.Except(file2Lines);
        IEnumerable<String> inSecondNotInFirst = file2Lines.Except(file1Lines);

谢谢你,祝你有美好的一天

您可以使用匿名类型和Enumerable.Join

var lines1 = file1Lines
    .Select(l => new { Line = l, Firstpart = l.Split('\\')[0].Trim() });
var lines2 = file2Lines
    .Select(l => new { Line = l, Firstpart = l.Split('\\')[0].Trim() });

var inFirstNotInSecond = lines1.Select(x => x.Firstpart)
    .Except(lines2.Select(x => x.Firstpart));
var inSecondNotInFirst = lines2.Select(x => x.Firstpart)
    .Except(lines1.Select(x => x.Firstpart));

IEnumerable<String> inFirstNotInSecondLines =
    from l1 in lines1
    join x1 in inFirstNotInSecond on l1.Firstpart equals x1
    select l1.Line;
IEnumerable<String> inSecondNotInFirstLines =
     from l2 in lines2
     join x2 in inSecondNotInFirst on l2.Firstpart equals x2
     select l2.Line;

您可以使用带有IEqualityComparerExcept的重载。 然后可以编写比较器以仅比较前20个字符之后的字符串。 这样, Except将比较前20个字符后的字符串,但实际上不会截断返回的值。

public class AfterTwenty : IEqualityComparer<string>
{
    public bool Equals(string x, string y)
    {
        if (x == null)
        {
            return y == null;
        }

        return x.Substring(20) == y.Substring(20);
    }

    public int GetHashCode(string obj)
    {
        return obj == null ? 0 : obj.Substring(20).GetHashCode();
    }
}

然后,您可以像这样调用Except

   var comparer = new AfterTwenty();
   var inFirstNotInSecond = file1Lines.Except(file2Lines, comparer);
   var inSecondNotInFirst = file2Lines.Except(file1Lines, comparer);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM