C# Select elements in list as List of string

后端 未结 2 1282
猫巷女王i
猫巷女王i 2020-12-03 02:18

In C# i need to get all values of a particular property from an object list into list of string

List emplist = new List()
           


        
相关标签:
2条回答
  • 2020-12-03 02:58
    List<string> empnames = emplist.Select(e => e.Ename).ToList();
    

    This is an example of Projection in Linq. Followed by a ToList to resolve the IEnumerable<string> into a List<string>.

    Alternatively in Linq syntax (head compiled):

    var empnamesEnum = from emp in emplist 
                       select emp.Ename;
    List<string> empnames = empnamesEnum.ToList();
    

    Projection is basically representing the current type of the enumerable as a new type. You can project to anonymous types, another known type by calling constructors etc, or an enumerable of one of the properties (as in your case).

    For example, you can project an enumerable of Employee to an enumerable of Tuple<int, string> like so:

    var tuples = emplist.Select(e => new Tuple<int, string>(e.EID, e.Ename));
    
    0 讨论(0)
  • 2020-12-03 03:03
    List<string> empnames = (from e in emplist select e.Enaame).ToList();
    

    Or

    string[] empnames = (from e in emplist select e.Enaame).ToArray();
    

    Etc...

    0 讨论(0)
提交回复
热议问题