如何比较C#中的2个字符串,然后在分隔符上拆分,合并(删除重复项)并对项目进行排序?
var str1 = "123ABC;789XYZ";
var str2 = "456CDE;123ABC;012ABC";
var result = str1.SplitSortAndMerge(str2); // => result = "012ABC;123ABC;456CDE;789XYZ"
答案 0 :(得分:8)
这应该对您有帮助。
var str2 = "456CDE;123ABC;012ABC";
var result = string.Join(";",str2.Split(new[]{";"},StringSplitOptions.RemoveEmptyEntries).Distinct().OrderBy(x=>x));
如果您需要包含str1,则
var str1 = "123ABC1";
var result = string.Join(";",str2.Split(new[]{";"},StringSplitOptions.RemoveEmptyEntries).Concat(new[]{str1}).Distinct().OrderBy(x=>x));
根据您上一次在OP中进行的更新,最好编写扩展方法。
public static class Extensions
{
public static string SplitAndSort(this IEnumerable<string> source)
{
var list = source.Where(x=>x!=null)
.SelectMany(c=>c.Split(new[]{";"},StringSplitOptions.RemoveEmptyEntries))
.Distinct()
.OrderBy(x=>x);
return string.Join(";",list);
}
}
现在您可以使用
var str1 = "123ABC1;012ABC";
var str2 = "456CDE;123ABC;123ABC;012ABC";
(new []{str1,str2}).SplitAndSort();
输出
012ABC;123ABC;123ABC1;456CDE
答案 1 :(得分:0)
var str2 = "456CDE;123ABC;012ABC";
var result = string.Join(";",str2.Split(';').Distinct().OrderBy(x => x).ToList());