【问题标题】:Match sections of a List, and Replace if both exist匹配列表的部分,如果两者都存在则替换
【发布时间】:2018-07-07 17:41:22
【问题描述】:

我在一个 List<> 中有来自不同国家/地区的约会。我正在尝试获取在第二个逗号之前包含相同字符的两条记录,并将这两项替换为新的。

例子:

从这里:

18/04/2014,Good Friday,England and Wales
18/04/2014,Good Friday,Scotland

进入这个:

18/04/2014,Good Friday,"England, Wales and Scotland"

请注意,列表中可能有多种情况,如上例。我已经设法在第二个逗号之前得到了所有东西:

splitSubstring = line.Remove(line.LastIndexOf(','));

我尝试了以下方法,但它显然存在缺陷,因为即使找到匹配项也不会删除两条记录:

foreach (var line in orderedLines)
{
    if (splitSubstring == line.Remove(line.LastIndexOf(',')))
        {
        //Replace if previous is match here
        }
    splitSubstring = line.Remove(line.LastIndexOf(','));
    File.AppendAllText(correctFile, line);
}

【问题讨论】:

  • 旁注:熟悉“C# LINQ 集合操作”(搜索它),对于以后的帖子,避免添加诸如“谢谢”和“搜索了很多”之类的文本 - meta.stackoverflow.com/search?q=remove+fluff。如果你想展示你的努力 - 显示你尝试过的代码(这篇文章中的一个与问题无关)。
  • 您真的想要18/04/2014,Good Friday,England, Wales and Scotland 还是18/04/2014,Good Friday,"England, Wales and Scotland" 更好(因为它是有效的CSV)?
  • 对不起,我错过了引号,会更新
  • @Enigmativity 你确实是对的——不知何故我读到 OP 有两个列表......这可能只是 .GroupBy 但解析/合并代码很痛苦,特别是因为常规 String.Join 不起作用...
  • @Alz_dev - 你的源文件是否也已经包含引号?

标签: c# list replace match


【解决方案1】:

我建议将其解析为您可以使用的结构,例如

public class HolidayInfo
{
    public DateTime Date { get; set; }
    public string Name { get; set; }
    public string[] Countries { get; set; }
};

然后

string[] lines = new string[]
{
    "18/04/2014,Good Friday,England and Wales",
    "18/04/2014,Good Friday,Scotland"
};

// splits the lines into an array of strings
IEnumerable<string[]> parsed = lines.Select(l => l.Split(','));
// copy the parsed lines into a data structure you can write code against
IEnumerable<HolidayInfo> info = parsed
    .Select(l => new HolidayInfo
    {
        Date = DateTime.Parse(l[0]),
        Name = l[1],
        Countries = l[2].Split(new[] {",", " and " }, StringSplitOptions.RemoveEmptyEntries)
    });

...等等。一旦你把它放在一个有用的数据结构中,你就可以开始开发所需的逻辑了。上面的代码只是一个例子,方法是你应该关注的。

【讨论】:

  • 这看起来比我做的更优雅 - 我会记下来以备不时之需,谢谢
  • @Alz_dev 在 Stack Overflow 上,而不仅仅是评论感谢,更好的表达感谢的方式是对答案进行投票和/或标记为答案以给予该人一些荣誉。
【解决方案2】:

我最终使用 LINQ 将 List 分开,然后根据 if 语句将它们 .Add() 放入另一个列表中。 LINQ 让它变得简单又好用。

//Using LINQ to seperate the two locations from the list. var seperateScotland = from s in toBeInsertedList where s.HolidayLocation == scotlandName select s;

var seperateEngland = from e in toBeInsertedList where e.HolidayLocation == engAndWales select e;

感谢您将我指向 LINQ

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-04
    • 1970-01-01
    • 2014-09-06
    • 1970-01-01
    • 1970-01-01
    • 2020-07-29
    • 2020-11-24
    • 1970-01-01
    相关资源
    最近更新 更多