In C# i need to get all values of a particular property from an object list into list of string
List emplist = new List()
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));
List<string> empnames = (from e in emplist select e.Enaame).ToList();
Or
string[] empnames = (from e in emplist select e.Enaame).ToArray();
Etc...