如何从列表中选择唯一元素{0, 1, 2, 2, 2, 3, 4, 4, 5}以便{0, 1, 3, 5}有效地删除重复元素的所有实例{2, 4}?
Bry*_*tts 32
var numbers = new[] { 0, 1, 2, 2, 2, 3, 4, 4, 5 };
var uniqueNumbers =
from n in numbers
group n by n into nGroup
where nGroup.Count() == 1
select nGroup.Key;
// { 0, 1, 3, 5 }
Run Code Online (Sandbox Code Playgroud)
CVe*_*tex 17
var nums = new int{ 0...4,4,5};
var distinct = nums.Distinct();
Run Code Online (Sandbox Code Playgroud)
确保你使用的是Linq和.NET framework 3.5.
Bar*_*Alp 12
随着lambda ..
var all = new[] {0,1,1,2,3,4,4,4,5,6,7,8,8}.ToList();
var unique = all.GroupBy(i => i).Where(i => i.Count() == 1).Select(i=>i.Key);
Run Code Online (Sandbox Code Playgroud)
Mat*_*lls 10
C#2.0解决方案:
static IEnumerable<T> GetUniques<T>(IEnumerable<T> things)
{
Dictionary<T, int> counts = new Dictionary<T, int>();
foreach (T item in things)
{
int count;
if (counts.TryGetValue(item, out count))
counts[item] = ++count;
else
counts.Add(item, 1);
}
foreach (KeyValuePair<T, int> kvp in counts)
{
if (kvp.Value == 1)
yield return kvp.Key;
}
}
Run Code Online (Sandbox Code Playgroud)
如果列表中有复杂的类型对象并希望获取属性的唯一值,则这是另一种方法:
var uniqueValues= myItems.Select(k => k.MyProperty)
.GroupBy(g => g)
.Where(c => c.Count() == 1)
.Select(k => k.Key)
.ToList();
Run Code Online (Sandbox Code Playgroud)
或者获得不同的值:
var distinctValues = myItems.Select(p => p.MyProperty)
.Distinct()
.ToList();
Run Code Online (Sandbox Code Playgroud)
如果您的属性也是复杂类型,则可以为Distinct()创建自定义比较器,例如Distinct(OrderComparer),其中OrderComparer可能如下所示:
public class OrderComparer : IEqualityComparer<Order>
{
public bool Equals(Order o1, Order o2)
{
return o1.OrderID == o2.OrderID;
}
public int GetHashCode(Order obj)
{
return obj.OrderID.GetHashCode();
}
}
Run Code Online (Sandbox Code Playgroud)