我有List<double[]>
我希望用数组创建新列表,女巫完全相同。我这样试试:
var query = li.GroupBy(x => x)
.Where(g => g.Count() > 1)
.Select(y => y.Key)
.ToList();
但是在所有列表查询都有0个元素之后......我做错了什么?
好的,所以:
list[0] = double[4] {1.4,0.5,3.6,1.2},
list[1] = double[4] {0.3,0.4,3.1,1.2}
list[2] = double[4] {1.4,0.5,3.6,1.2}
在我的新名单中,我只想:
new_list[0] = double[4] {1.4,0.5,3.6,1.2}
答案 0 :(得分:1)
List<double[]> lists = new List<double[]>{
new[]{1.4,0.5,3.6,1.2},
new[]{0.3,0.4,3.1,1.2},
new[]{1.4,0.5,3.6,1.2}
};
var query = lists.SelectMany(x => x) // <-- You need this
.GroupBy(x => x)
.Where(g => g.Count() > 1)
.Select(y => y.Key)
.ToList();
答案 1 :(得分:1)
当它们是复杂对象(如数组)时,您应该使用自定义相等比较器来查找重复项。
class DoubleArrayComparer : IEqualityComparer<double[]>
{
private DoubleArrayComparer() { }
public static readonly DoubleArrayComparer Instance = new DoubleArrayComparer();
public bool Equals(double[] x, double[] y)
{
return Enumerable.SequenceEqual(x, y);
}
public int GetHashCode(double[] obj)
{
//TODO: should implement better
return 0;
}
}
static void Main(string[] args)
{
List<double[]> li = new List<double[]>{
new[]{1.4,0.5,3.6,1.2},
new[]{0.3,0.4,3.1,1.2},
new[]{1.4,0.5,3.6,1.2}
};
var query = li.GroupBy(x => x, DoubleArrayComparer.Instance)
.Where(g => g.Count() == 1)
.Select(y => y.Key)
.ToList();
}
答案 2 :(得分:0)
如果我正确理解您的问题,您只需要在输入查询中重复的数组。因为没有简单的方法可以按整个数组内容进行分组,所以您可以尝试将数组转换为字符串并按该字符串分组:
var results = list.GroupBy(a => String.Join(",", a.Select(d => d.ToString())))
.Where(g => g.Count() > 1)
.Select(g => g.First())
.ToList();
答案 3 :(得分:0)
这个解决方案怎么样?
public class ArrayComparer : IEqualityComparer<double[]>
{
public bool Equals(double[] x, double[] y)
{
return x.SequenceEqual(y);
}
public int GetHashCode(double[] obj)
{
return base.GetHashCode();
}
}
var list = new double[] {1.4, 0.5, 3.6, 1.2};
var list2 = new double[] { 0.3, 0.4, 3.1, 1.2 };
var list3 = new double[] { 1.4, 0.5, 3.6, 1.2 };
var lst = new List<double[]> {list, list2, list3};
var newList = lst.Where(x => lst.Except(new List<double[]> {x}).Contains(x,new ArrayComparer()))
.Distinct(new ArrayComparer())
.ToList();
调试中的另一个例子:
答案 4 :(得分:-2)
var query = lists.Select(x => x)
.Where(y => x.Intersect(y).Count == x.Count)
.Select(y => y)
.ToList();