Home > Net >  Method to return a List<T> from a List<OwnStruct>, where List<T> then contains onl
Method to return a List<T> from a List<OwnStruct>, where List<T> then contains onl

Time:10-07

I'm struggling with this a little. I have a List<HeadStruc_Table> within my program.

The Class HeadStruct looks like following:

public partial class HeadStruct_Table : IComparable<HeadStruct_Table>
    {
        public string colName { get; set; }
        public string colName_edit { get; set; }
        public string alternativeNames { get; set; }
        public int Table_ID { get; set; }
        public bool colFound { get; set; }
        public CheckBox cBox { get; set; }

I don't know how to create a method with parameters (List<HeadStruct_Table>, HeadStruct_Table.colName) that then returns a List<TypeOf(HeadStruct_Table.colName)> containing only the values of colName in this specific case. Of course it should work for the bool and even CheckBox property as well.

As parameter HeadStruct_Table.colName doesn't work right now, as it is declared as just public and not public static, do i have to declare it as public static or is there any other chance to pass the specific property. Maybe by using a predicate?

That's the way it maybe could look like later?

public static IList<T> getList<T>(List<HeadStruct_Table> list, Func<HeadStruct_Table, T> getType)
    {
        var newList = new List<T>();

I just don't know how to get the special property and then, in the method, just read out those values. I wouldn't like to work with a string as parameter if it works without.

Anyone who has an idea?

That is my first question. I'm open for any advice to improve asking a question in here. Thank You.

CodePudding user response:

LINQ's Enumerable.Select method already does what you want:

var newList = list.Select(x => x.colName).ToList();
  • Related