I need a way of finding a matching row in an object list based on multiple key words. In the code example below, the FindID() function is the one I need to implement.
The rules are:
- Some of the rows in the table have * as the value (wildcard), which means they would match any value.
- The priority of matching is from left to right (i.e., it is more important to match values on the left side)
Some examples:
FindID("John", "Black", "Brown"); – should return 1, complete match
FindID("John", "Red", "Green"); – should return 5 (not 7), matched on “John” and the other two wildcards (*)
FindID("John", "Red", "Brown"); – should return 6, matched on “John” and “Brown” and one wildcard
FindID("Brian", "Grey", "Grey"); – should return 8, matched on three wildcard
The code below is complete and can be executed.
Does anyone know the best way of doing this?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TableScan
{
class Program
{
public static TableClass _MyTable = new TableClass();
public class TableRow
{
public int ID;
public string Name;
public string Hair;
public string Eyes;
public TableRow(int _ID, string _Name, string _Hair, string _Eyes)
{
ID = _ID;
Name = _Name;
Hair = _Hair;
Eyes = _Eyes;
}
}
public class TableClass
{
public List<TableRow> Table = new List<TableRow>();
}
static void Main(string[] args)
{
// ID Name Hair Eyes
// 1 John Black Brown
// 2 Paul Brown Green
// 3 Ringo Blond Blue
// 4 George Red Blue
// 5 John * *
// 6 John * Brown
// 7 * Red *
// 8 * * *
// 9 Paul * *
CreateTable();
ShowTable();
FindID("John", "Black", "Brown"); // should return 1, complete match
FindID("John", "Red", "Green"); // should return 5 (not 7), matched on "John" and the other two wildcards (*)
FindID("John", "Red", "Brown"); // should return 6, matched on "John" and "Brown" and one wildcard
FindID("Brian", "Grey", "Grey"); // should return 8, matched on three wildcard
while (Console.ReadKey().Key == 0) { }
}
static int FindID(string _Name, string _Hair, string _Eyes)
{
// needs to be implemented
return 0;
}
static void CreateTable()
{
_MyTable.Table.Add(new TableRow(1, "John", "Black", "Brown"));
_MyTable.Table.Add(new TableRow(2, "Paul", "Brown", "Green"));
_MyTable.Table.Add(new TableRow(3, "Ringo", "Blond", "Blue"));
_MyTable.Table.Add(new TableRow(4, "George", "Red", "Blue"));
_MyTable.Table.Add(new TableRow(5, "John", "*", "*"));
_MyTable.Table.Add(new TableRow(6, "John", "*", "Brown"));
_MyTable.Table.Add(new TableRow(7, "*", "Red", "*"));
_MyTable.Table.Add(new TableRow(8, "*", "*", "*"));
_MyTable.Table.Add(new TableRow(9, "Paul", "*", "*"));
}
static void ShowTable()
{
foreach(TableRow _TableRow in _MyTable.Table)
{
Console.WriteLine("{0} {1} {2} {3}", _TableRow.ID, _TableRow.Name, _TableRow.Hair, _TableRow.Eyes);
}
}
}
}
ok pretty dead tonight, here’s a solution based on comment see http://ideone.com/rR46Ws