C# 在列表中查找对象<;对象>;以同样的性质
我正在创建一个包含不同对象的列表C# 在列表中查找对象<;对象>;以同样的性质,c#,linq,C#,Linq,我正在创建一个包含不同对象的列表list,我需要对它们使用linq 所有对象都有一个“name”属性,下面是一些类对象: class project_node { public string name { get;set; } // SAME public int level{ get; set; } public compiler_enum compiler{ get; set; } } class resourc
list
,我需要对它们使用linq
所有对象都有一个“name”属性,下面是一些类对象:
class project_node
{
public string name { get;set; } // SAME
public int level{ get; set; }
public compiler_enum compiler{ get; set; }
}
class resource_node
{
public string name { get;set; } // SAME
public int level{ get; set; }
public byte[] resource_data { get; set; }
public compiler_enum compiler{ get; set; }
}
class codeblock_node
{
public string name { get;set; } // SAME
public string filename{ get;set; }
public int level{ get; set; }
public string code{ get; set; }
public compiler_enum compiler{ get; set; }
}
所以我的列表有一些项目节点,一些资源节点和一些代码块节点
项目文件列表的声明
:
List<object> project_file_list = new List<object>{};
您可以使用如下界面:
interface IHaveName
{
string name {get;}
}
class A
{
public string Name { get; set; }
public int Score { get; set; }
}
class B
{
public string Name { get; set; }
public int Value { get; set; }
}
var items = new List<object>()
{
new B { Name = "B", Value = 1 },
new B { Name = "A", Value = 2 }
};
var target = new A { Name = "A", Score = 1 };
object match = items
.Find(o => o.GetType().GetProperty("Name").GetValue(o) == target.Name );
//Here would be your object
然后,您的所有对象都可以实现此接口:
class project_node: IHaveName
{ … }
您的列表应该是IHaveName列表,而不是object列表
List<IHaveName> project_file_list = new List<IHaveName>
… etc...
List项目\文件\列表=新列表
……等等。。。
而且你的LINQ也会工作。因为你正在制作一个通用对象的列表,所以你不能像通常那样进入相应的属性 你可以这样做:
interface IHaveName
{
string name {get;}
}
class A
{
public string Name { get; set; }
public int Score { get; set; }
}
class B
{
public string Name { get; set; }
public int Value { get; set; }
}
var items = new List<object>()
{
new B { Name = "B", Value = 1 },
new B { Name = "A", Value = 2 }
};
var target = new A { Name = "A", Score = 1 };
object match = items
.Find(o => o.GetType().GetProperty("Name").GetValue(o) == target.Name );
//Here would be your object
A类
{
公共字符串名称{get;set;}
公共整数分数{get;set;}
}
B类
{
公共字符串名称{get;set;}
公共int值{get;set;}
}
var items=新列表()
{
新的B{Name=“B”,值=1},
新的B{Name=“A”,值=2}
};
var target=newa{Name=“A”,分数=1};
对象匹配=项目
.Find(o=>o.GetType().GetProperty(“名称”).GetValue(o)==target.Name);
//这是你的目标
您的代码有什么问题。@Generalfindobj
没有name
属性。请显示project\u file\u list
@General添加的声明。list
很少是存储任何内容的好方法,如果您需要查询某个属性,那么最好为这些属性创建一个接口有时我觉得太愚蠢了:(!谢谢,接受了。