所以你需要一种方法来根据多列检测重复并且顺序无关紧要?你可以使用这个类:
public class MultiFieldIgnoreOrderComparer : IEquatable<IEnumerable<object>>, IEqualityComparer<IEnumerable<object>>
{
private IEnumerable<object> objects;
public MultiFieldIgnoreOrderComparer(IEnumerable<object> objects)
{
this.objects = objects;
}
public bool Equals(IEnumerable<object> x, IEnumerable<object> y)
{
return x.All(y.Contains);
}
public int GetHashCode(IEnumerable<object> objects)
{
unchecked
{
int detailHash = 0;
unchecked
{
// order doesn't matter, so we need to order:
foreach (object obj in objects.OrderBy(x => x))
detailHash = 17 * detailHash + (obj == null ? 0 : obj.GetHashCode());
}
return detailHash;
}
}
public override int GetHashCode()
{
return GetHashCode(this.objects);
}
public override bool Equals(object obj)
{
MultiFieldIgnoreOrderComparer other = obj as MultiFieldIgnoreOrderComparer;
if (other == null) return false;
return this.Equals(this.objects, other.objects);
}
public bool Equals(IEnumerable<object> other)
{
return this.Equals(this.objects, other);
}
}
你可以这样使用它:
var recentchats = MessagesCollection.AsQueryable()
.Where(x => x.CA == 1 || x.CB == 1)
.GroupBy(x => new MultiFieldIgnoreOrderComparer(new[] { x.CA, x.CB }))
.Select(g => g.First())
.ToList();