我要在两个列表之间进行比较,对于找到的每个项目,我必须从第二个列表返回一个属性,我想通过 LINQ 来完成。
我有这门课:
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; }
}
我有同一个班级的名单:
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);
我还有一个字符数组:
char[] charArray = new[] { 'c', 'a', 'a', 'f' };
我想从 char 数组中获取每个项目,使用 Data 属性搜索 Table 列表,如果找到匹配项,则返回 HexToInt 值。此返回必须在列表中,上面是对象的返回列表的示例:
列表:[2,0,0,5]
我尝试了这个,但它不起作用,因为在这种情况下无法访问十六进制属性:
var test2 = dteCharArray.Where(x => table.Any(y => y.Data == x.ToString())).Select(y => y.Hex).ToList();
这将必须搜索 tableList 中的条目:
charArray.Select(x => tableList.FirstOrDefault(y => y.Data == x.ToString())?.HexToInt).ToList();