我有一个字符串C#列表,如下所示:
var list = new List<string>() { "A", "B", "C", "B", "C", "B", "D" };
我只想保留该列表中的唯一项目,以及多次删除的所有项目。
在这个例子中,它将是&#34; A&#34;和&#34; D&#34;在删除所有重复项之后离开。
答案 0 :(得分:9)
这个怎么样:
var tmp = myList.GroupBy(x => x).Where(x => x.Count() == 1);
这将只返回那些恰好出现一次的条目。不返回具有重复项的条目。
现在简单地将该组列表压缩成如下:
var result = tmp.Select(x => x.Key).ToList();
答案 1 :(得分:4)
list.GroupBy(x => x) //group the items together with themselves as the key
.Where(g => g.Count() == 1) // select only those groups with only one element
.Select(g => g.Key) // get the key out (.First() and .FirstOrDefault()
// would also work in this case, .Key tends to be a tiny bit faster).
.ToList() // create a new list (if really necessary,
// if you can skip this step do and things will be faster).
答案 2 :(得分:3)
var list = new List<string> { "A", "B", "C", "B", "C", "B", "D" };
list = list.GroupBy(x => x).Where(g => g.Count() == 1).SelectMany(g => g).ToList();
您可以使用linq执行此操作。
答案 3 :(得分:0)
var list = new List<string> { "A", "B", "C", "B", "C", "B", "D" };
var NewList = list.Except(list.GroupBy(i => i).Where(x=>x.Count()>1)
.Select(ss => ss.FirstOrDefault()))
.ToList();
答案 4 :(得分:0)
List<string> list = new List<string>() { "A", "B", "C", "B", "C", "B", "D"};
for (int i = 0; i < list.Count; i++)
{
string x = list.ElementAt(i);
int count = 0;
for (int j = 0; j < list.Count; j++)
{
if (list.ElementAt(j).Equals(x))
{
count++;
if (count>1)
{
list.RemoveAll(y => y.Equals(x));
count = 0;
}
}
}
}
试试这个...... 列表末尾只包含“A”“D”