I have a comparison to make between two lists, and for each item found, I have to return a property from the second list, I would like to do it via LINQ.
I have this class:
class Table
{
private int hexToInt = 0;
private string data = string.Empty;
public int HexToInt { get => hexToInt; set => hexToInt = value; }
public string Data { get => data; set => data = value; }
public string Hex { get => hexToInt.ToString("X"); }
public int HexSizeInBytes { get => Hex.Length / 2; }
}
I have a list of this same class:
List<Table> tableList = new List<Table>();
Table table = new Table();
table.HexToInt = 0;
table.Data = "a";
tableList.Add(table);
table = new Table();
table.HexToInt = 1;
table.Data = "b";
tableList.Add(table);
table = new Table();
table.HexToInt = 2;
table.Data = "c";
tableList.Add(table);
table = new Table();
table.HexToInt = 3;
table.Data = "d";
tableList.Add(table);
table = new Table();
table.HexToInt = 4;
table.Data = "d";
tableList.Add(table);
table = new Table();
table.HexToInt = 5;
table.Data = "f";
tableList.Add(table);
table = new Table();
table.HexToInt = 6;
table.Data = "g";
tableList.Add(table);
I also have a char array:
char[] charArray = new[] { 'c', 'a', 'a', 'f' };
I would like to take each item from the char array, search the Table list using the Data property, and if a match is found, return the HexToInt value. This return must be in a list, an example of the return list for the objects above:
List: [2, 0, 0, 5]
I tried this, but it doesn’t work, because the Hex property is inaccessible in this context:
var test2 = dteCharArray.Where(x => table.Any(y => y.Data == x.ToString())).Select(y => y.Hex).ToList();
>Solution :
This will have to search the entry in tableList:
charArray.Select(x => tableList.FirstOrDefault(y => y.Data == x.ToString())?.HexToInt).ToList();