How can I optimize this code to increase the performance of searching data?
public class TableRowInfo : IEquatable<GridRowInfo>
{
#region Ctor
public TableRowInfo(int rowIndex, object rowData, NodeEntry nodeEntry, bool isNewRow = false)
{
this.RowData = rowData;
this.NodeEntry = nodeEntry;
this.RowIndex = rowIndex;
this.IsNewRow = isNewRow;
}
public TableRowInfo(int rowIndex, bool isNewRow)
{
this.RowData = null;
this.NodeEntry = null;
this.RowIndex = rowIndex;
this.IsNewRow = isNewRow;
}
#endregion
#region Properties
public object RowData { get; private set; }
public bool IsDataRow
{
get { return RowData != null; }
}
public bool IsNewRow
{
get;
set;
}
public int RowIndex { get; internal set; }
internal NodeEntry NodeEntry { get; private set; }
#endregion
public override int GetHashCode()
{
int rowDataHashCode = this.RowData == null ? 0 : this.RowData.GetHashCode();
return rowDataHashCode ^ this.RowIndex;
}
#region IEquatable<TableRowInfo> Members
public bool Equals(GridRowInfo other)
{
if (Object.ReferenceEquals(other, null)) return false;
if (Object.ReferenceEquals(this, other)) return true;
if (!this.IsDataRow == other.IsDataRow)
return false;
else if (this.IsDataRow)
return this.RowData == other.RowData;
else
return this.RowIndex == other.RowIndex;
}
#endregion
}
public class TableSelectedRowsCollection : List<TableRowInfo>
{
#region Ctor
public TableSelectedRowsCollection()
{
}
#endregion
#region IList Members
public bool Contains(TableRowInfo rowInfo)
{
if (rowInfo.IsNewRow)
return Find(rowInfo.RowIndex) != null;
else
return Find(rowInfo.NodeEntry) != null;
}
public bool Contains(int rowIndex)
{
return Find(rowIndex) != null;
}
public bool Contains(object rowData)
{
return Find(rowData) != null;
}
public bool Contains(NodeEntry nodeEntry)
{
return Find(nodeEntry) != null;
}
#endregion
#region Helper Methods
internal TableRowInfo Find(NodeEntry nodeEntry)
{
if (nodeEntry != null && this.Count > 0)
{
return this.FirstOrDefault(rowInfo => rowInfo.NodeEntry == nodeEntry);
}
return null;
}
internal TableRowInfo Find(int rowIndex)
{
if (rowIndex > 0 && this.Count > 0)
{
return this.FirstOrDefault(rowInfo => rowInfo.RowIndex == rowIndex);
}
return null;
}
internal TableRowInfo Find(object rowData)
{
if (rowData != null && this.Count > 0)
{
return this.FirstOrDefault(rowInfo => rowInfo.RowData == rowData);
}
return null;
}
internal TableRowInfo Find(TableRowInfo rowInfo)
{
if (rowInfo != null && this.Count > 0)
{
return this.FirstOrDefault(item => item.NodeEntry == rowInfo.NodeEntry);
}
return null;
}
internal List<int> GetRowIndexes()
{
var rowIndexes = new List<int>();
if (this.Count > 0)
{
this.ForEach(rowInfo => rowIndexes.Add(rowInfo.RowIndex));
}
return rowIndexes;
}
#endregion
}
List
- search is O(n) = n. Try using some sorted structure instead, that has O(n) = lg(n). Some binary tree, sorted dictionary or something like that. \$\endgroup\$