如何比较两个逗号分隔的字符串值并在现有列表的相同位置更新?

时间:2018-11-13 10:17:11

标签: c# linq

我有一个包含一些值的字符串列表,我想从列表中比较2个位置的值,并从列表中删除匹配项。

代码:

var list = new List<string>();
 list.Add("Employee1");
 list.Add("Account");
 list.Add("100.5600,A+   ,John");
 list.Add("1.00000,A+     ,John");
 list.Add("USA");

现在我想比较第二和第三位置:

list.Add("100.5600,A+   ,John");
list.Add("1.00000,A+     ,John");

比较上述2条记录,并删除匹配的记录,如下所示:

预期输出:

list.Add("100.5600");
list.Add("1.00000");

这就是我试图做的事情:

 var source = list[2].Split(',').Select(p => p.Trim());
 var target = list[3].Split(',').Select(p => p.Trim());
 var result = source.Except(target);

但是问题是我只得到100.5600作为输出。

是否可以比较和更新现有列表中不匹配的记录?

2 个答案:

答案 0 :(得分:2)

这个“美女”怎么样

array()

编辑-保留原始顺序:

var list = new List<string>();
list.Add("Employee1");
list.Add("Account");
list.Add("100.5600,A+   ,John");
list.Add("1.00000,A+     ,John");
list.Add("USA");

//prepare the list, I decided to make a tuple with the original string in the list and the splitted array
var preparedItems = list.Select(x => (x, x.Split(',')));

//group the prepared list to get matching items for the 2nd and 3rd part of the split, I therefor used .Skip(1) on the previously prepared array
var groupedItems = preparedItems.GroupBy(x => string.Join(",", x.Item2.Skip(1).Select(y => y.Trim())));

//"evaluate" the group by saying if the items in the group is > 1 only use the first part of the prepared array and if it doesnt have more than one entry use the orignal string 
var evaluatedItems = groupedItems.SelectMany(x => x.Count() > 1 ? x.Select(y => y.Item2[0]) : x.Select(y => y.Item1));

//replace the orignal list with the new result
list = evaluatedItems.ToList();

答案 1 :(得分:1)

您可以通过检查其中一个项目是否不包含在另一个项目中来轻松获得它:

   var result = source.Where(x => !target.Contains(x));

要更新您的旧列表,请执行以下操作:

  var source = string.Join(",", source.Where(x => !target.Contains(x)));