匹配List的部分,如果两者都存在则替换

时间:2018-01-29 04:12:54

标签: c# list replace match

我在一个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);
}

2 个答案:

答案 0 :(得分:0)

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

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

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

答案 1 :(得分:0)

我最终使用LINQ将List和.Add()拆分为基于if语句的另一个。 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