我使用以下代码创建一个数组来查找多维数组的开始和结束索引:
var valueArray = Enumerable.Range(0, val.GetLength(1))
.Where(index => val[0, index].Contains("Rak"))
.ToArray();
我正在使用valueArray获取起始索引,即valueArray [0]和结束索引,它将是valueArray [valueArray.Length-1]。
以上代码有效。但看起来它正在为获得开始和结束索引做大量的工作。因为它首先创建valueArray,然后输入所有值,然后获取索引值。任何人都可以建议更好的方法吗?
数组的定义:
private string[,] _val;
public string[,] val
{
[Pure]
get
{
if (_val != null)
return (string[,])_val.Clone();
return null;
}
set
{
_val = value;
}
}
答案 0 :(得分:1)
我宁愿选择这样的东西:
public class CellInfo
{
public int Row { get; set; }
public int Column { get; set; }
public string Value { get; set; }
}
示例:
List<CellInfo> _cells = new List<CellInfo>();
public void Example()
{
_cells.Add(new CellInfo { Column = 6, Row = 3, Value = "Rak" });
_cells.Add(new CellInfo { Column = 3, Row = 8, Value = "Rak" });
_cells.Add(new CellInfo { Column = 2, Row = 4, Value = "Rak" });
_cells.Add(new CellInfo { Column = 5, Row = 7, Value = "Sac" });
_cells.Add(new CellInfo { Column = 1, Row = 3, Value = "Sac" });
int[] rowRakAtColumn0 = _cells.Where(cell => cell.Column == 0
&& cell.Value.Contains("Rak"))
.OrderBy(cell => cell.Row)
.Select(cell => cell.Row)
.ToArray();
CellInfo[] row0Values = _cells.Where(cell => cell.Row == 0)
.OrderBy(cell => cell.Column)
.ToArray();
}
将其转换为多数组(如果需要)
public string[,] ToMultiArray(List<CellOffset> cells)
{
string[,] multiDimentional = new string[
cells.Max(cell => cell.Column), cells.Max(cell => cell.Row)];
cells.ForEach(cell =>
multiDimentional[cell.Column, cell.Row] = cell.Value);
return multiDimentional;
}
string[,] values = ToMultiArray(_cells);
回答lazzy_ms:
linq .Select()
方法也可以将索引作为lambda函数的第二个参数传递。您只需要在匿名类中捕获它。
var result = _cells
// here and capture it in an object
// |
.Select((Item, Index) => new { Item, Index })
.FirstOrDefault(itemWithIndex => itemWithIndex.Item.Column == 5);
Console.WriteLine($"The index of column 5 is {result?.Index}");
确保在进行任何过滤之前选择索引。否则它不会匹配
答案 1 :(得分:0)
优化代码的一种方法是分别从开头和结尾搜索第一个和最后一个元素。
int firstIndex;
int lastIndex;
for(int i = 0; i < val.GetLength(1); i++)
{
if(val[0,i].Contains("Rak"))
{
firstIndex = i;
break;
}
}
for(int i = val.GetLength(1) - 1; i>=0; i--)
{
if(val[0,i].Contains("Rak"))
{
lastIndex = i;
break;
}
}