Reputation:
I'm creating a list with different objects List<object>
and I need to use linq on them.
All objects have a "name" property , Here's some class objects :
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; }
}
So my list has some project_node , some resource_node and some codeblock_node...
Declaration of project_file_list
:
List<object> project_file_list = new List<object>{};
How can I use linq to find and match name in my list ? something like this :
object find_target = project_file_list.Find(findobj => findobj.name == "Name");
Upvotes: 1
Views: 512
Reputation: 106
Since you are making a list of generic object you wouldn't be able to get into the corresponding property like you usually do.
You could do something like this:
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
Upvotes: 0
Reputation:
You can use an interface, something like this:
interface IHaveName
{
string name {get;}
}
Then, all your objects can implement this interface:
class project_node: IHaveName
{ … }
And your list should be a List of IHaveName instead of List of object
List<IHaveName> project_file_list = new List<IHaveName>
… etc...
and your LINQ will work.
Upvotes: 1