C# Select elements in list as List of string
In C# i need to get all values of a particular property from an object list into list of string
List<Employee> emplist = new List<Employee>()
{
new Employee{ EID=10, Ename="John"},
new Employee{ EID=11, Ename="Adam"},
new Employee{ EID=12, Ename="Ram"}
};
List<string> empnames = emplist.//get all Enames in 'emplist' object into list
//using linq or list functions or IENumerable functions
I am familiar with the foreach method to extract the value but I want to know if \ how its possible use linq or IENumerable functions or some shorter code to extract values from the list object property values into a string object.
My query is Similar to C# select elements from IList but i want the the result as list of string
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...