Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to compare 2 objects and return a property of the second object that is not in the comparison

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading