假设我有多维对象数组,表示简单矩阵
Object[,] mybaseobject = new object[,] {
{"Rakesh", "Martin", "21"},
{"Rohith", "M", "22"},
{"Rakesh", "Martin", "21"},
{"varsha", "MJ", "18"},
即使String对象[,]也适合我的项目
It Object数组看起来像
Rakesh Martin 21
Rohith M 22
Rakesh Martin 21
Rohith M 22
varsha Mj 18
Rohith M 22
请找我删除重复行的方法,并让数组看起来像这样?
Rakesh Murthy 21
Rohith M 22
varsha Mj 18
我正在使用这种方法[堆栈溢流论坛中的现有方法之一] [1]
Delete duplicate rows from two dimentsional array
但是abovelink对于多维整数数据工作正常我需要多维对象数组的解决方案[,]
请提前帮助我(+1)
答案 0 :(得分:0)
取决于帖子delete-duplicate-rows-from-two-dimentsional-array 您可以创建列表列表,然后使用自定义IEqualityComparer实现,之后获取不同的值。最短的代码:
static void Main(string[] args)
{
var mybaseobject = new object[,]
{
{"Ranjith", "Murthy", "21"},
{"Rohith", "M", "22"},
{"Ranjith", "Murthy", "21"},
{"varsha", "MJ", "18"}
};
var res = ToEnumerableOfEnumerable(mybaseobject).ToList();
var dist = res.Distinct(new SimpleComparer());
}
public class SimpleComparer : IEqualityComparer<List<object>>
{
public bool Equals(List<object> x, List<object> y)
{
var l1 = x[0];
var l2 = x[1];
var r1 = y[0];
var r2 = y[1];
return r1 + "" == l1 + "" && l2 + "" == r2 + "";
}
public int GetHashCode(List<object> obj)
{
return 0;
}
}
public static IEnumerable<List<T>> ToEnumerableOfEnumerable<T>(T[,] array)
{
int rowCount = array.GetLength(0);
int columnCount = array.GetLength(1);
for (int rowIndex = 0; rowIndex < rowCount; rowIndex++)
{
var row = new List<T>();
for (int columnIndex = 0; columnIndex < columnCount; columnIndex++)
{
row.Add(array[rowIndex, columnIndex]);
}
yield return row;
}
}
答案 1 :(得分:0)
正如其他人所指出的那样,您可能不想使用object[,]
。以下是将object[,]
转换为List<object[]>
,对其执行过滤,然后将List<object[]>
转换回二维数组的实现。
void Filter()
{
Object[,] mybaseobject = new object[,]
{
{ "Ranjith", "Murthy" },
{ "Rohith", "M" },
{ "Ranjith","Murthy" },
{ "varsha", "MJ" }
};
var objectList = AsList(mybaseobject);
var distinctLines = new List<object[]>();
foreach (var line in objectList)
{
if (!distinctLines.Any(x => x.SequenceEqual(line)))
{
distinctLines.Add(line);
}
}
var filteredobjects = AsTwoDimentionalArray(distinctLines);
}
private List<object[]> AsList(object[,] input)
{
var lines = new List<object[]>();
for(var i = 0; i < input.GetLength(0);++i)
{
var line = new List<object>( input.GetLength(1));
for (var j = 0; j < input.GetLength(1); ++j)
{
line.Add(input[i, j]);
}
lines.Add(line.ToArray());
}
return lines;
}
private object[,] AsTwoDimentionalArray(List<object[]> input)
{
var result = new object[input.Count(), input[0].Length];
for (var i = 0; i < input.Count; ++i)
{
for(var j = 0; j < input[0].Length; ++j)
{
result[i, j] = input[i][j];
}
}
return result;
}