简体   繁体   中英

Access the field value from IList in c#

I have a IList<T> which has data and i want to access the field value from the IList.

I have written below code to get field value

IList<T> source;
source.FirstOrDefault().Field("ParentID")

I want to access ParentID field value.

But it is giving following error while building the solution:

"'T' does not contain a definition for 'Field' and no extension method 'Field' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?)"

I have added System.Xml, System.Xml.Linq and System.Collections.Generic assembly, but still it doesn't work. Can anybody help?

Here is some generics 101.

Let's say you had a class named Node , which contained a property named ParentID .

public class Node 
{
    public int ParentId { get; set; }
}

Now you define a list of nodes. Basically an array of objects. In List<T> the T refers to the type of objects in your list. So you would define it as such:

IList<Node> source;

Then you would need to populate your list named source .

And then you could select the ParentId with the code you wrote.

source.FirstOrDefault().Field("ParentID")

将source.FirstOrDefault()强制转换为适当的类,例如: ((Employee)source.FirstOrDefault()).Field("ParentID")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM