假设我有一个类似的序列:-
1;2;3;4;5;6;7;8;9
现在我想删除一些(3, 6, 7)
,所以顺序如下:-
1;2;4;5;8;9
现在,如果我添加已删除的“否”,请再说(3, 6)
,这将给我类似的顺序:-
1;2;3;4;5;6;8;9 // 7 is not here
答案 0 :(得分:4)
将string
变成IEnumerable<T>
并使用 Linq ;最后在string
的帮助下将序列转回Join
:
string source = "1;2;3;4;5;6;7;8;9";
int[] exclude = new int[] {3, 6, 7};
int[] include = new int[] {3, 6};
var seq = source
.Split(';')
.Select(item => int.Parse(item)) // now we have IEnumerable<int>
.Where(item => !exclude.Contains(item)) // removing "exclude"
.Concat(include) // appending "include"
.OrderBy(item => item);
string result = string.Join(";", seq); // back to string
编辑:如果您正在使用集(无重复项),则可以尝试HashSet<T>
例如
string source = "1;2;3;4;5;6;7;8;9";
int[] exclude = new int[] { 3, 6, 7 };
int[] include = new int[] { 3, 6 };
HashSet<int> hs = new HashSet<int>(source
.Split(';')
.Select(item => int.Parse(item)));
hs.ExceptWith(exclude);
hs.UnionWith(include);
string result = string.Join(";", hs.OrderBy(item => item));
编辑2 :如果我们想在排除时处理重复,例如
string source = "1;2;3;3;3;3;7;8;9";
// Remove just 2 of existing 3
// We should get "1;2;3;3;7;8;9";
int[] exclude = new int[] { 3, 3, 7 };
int[] include = new int[] { 3, 6 };
我建议使用GroupBy
而不是Where
:
var seq = source
.Split(';')
.Select(item => int.Parse(item)) // now we have IEnumerable<int>
.GroupBy(item => item) // removing "exclude"
.SelectMany(chunk => chunk
.Skip(exclude.Count(item => item == chunk.Key)))
.Concat(include) // appending "include"
.OrderBy(item => item);
string result = string.Join(";", seq);