score:6
there are two options:
if you can implement an interface on the entity
public interface iselectable
{
string name { get; }
int id { get; }
}
public static list<selectlistitem> toselectitemlist<t>(this ienumerable<t> collection)
where t: iselectable
{
return collection.select(m => new selectlistitem
{
text = m.name,
value = m.id.tostring()
}).tolist();
}
using delegates
public static list<selectlistitem> toselectitemlist<t>(this ienumerable<t> collection, func<t, string> namegetter, func<t, int> idgetter)
{
return collection.select(m => new selectlistitem
{
text = namegetter(m),
value = idgetter(m).tostring()
}).tolist();
}
usage :
m.employmentstatus.toselectitemlist(e => e.name, e => e.id);
the second option is more verbose to use, but you get a ton more flexibility, since you don't have to clutter your data model with useless interface implementation, and you are free to use any property names for name
or id
score:3
dropdownlistfor
requires aienumerable<selectlistitem>
selectlist as a collection
there's already a class for that, namely selectlist
:
var selectlistitems = new selectlist(items, "id", "name");
no need for new extension methods whatsoever. i thought selectlist()
also has an overload with expressions for the key/value members instead of strings, but i may have found that somewhere else.
score:8
you can define an interface for all entities that you are going to use for dropdownlists like
public interface idropdownitem
{
int id {get; set;}
string name {get; set;}
}
then
public static list<selectlistitem> toselectitemlist<t>(ienumerable<t> collection)
where t : idropdownitem
{
return collection.select(m => new selectlistitem
{
text = m.name,
value = m.id.tostring()
}).tolist();
}
it would be better to make toselectitemlist
as extension method:
public static class enumerableextensions
{
public static list<selectlistitem> toselectitemlist<t>(this ienumerable<t> collection)
where t : program
{
return collection.select(m => new selectlistitem
{
text = m.name,
value = m.id.tostring()
}).tolist();
}
}
Source: stackoverflow.com
Related Query
- Generic ToSelectListItem method
- Code equivalent to the 'let' keyword in chained LINQ extension method calls
- Calling generic method with a type argument known only at execution time
- Cast Entity to Implemented Interface in a Generic Method Using LINQ for Entity Framework
- Enumerable.Empty<T>().AsQueryable(); This method supports the LINQ to Entities infrastructure and is not intended to be used directly from your code
- Visual Studio Code Analysis Rule - "Do not expose generic lists"
- How can I write a generic extension method for converting a delimited string to a list?
- LINQ WHERE method alters source collection
- C# Abstract Generic Method
- Expression<Func<T,bool>> adds an unwanted Convert when created in generic method
- It is possible to create a generic search method where key is unknown
- How do I build Expression Call for Any Method with generic parameter
- Execute method for each object in generic list using lambda
- LINQ Source Code Available
- Call Ignore Case for Contains Method using a generic LINQ Expression
- Is it possible to make 1 generic method out of these 2 linq statements?
- Call Generic Method with an anonymous Type (C#)
- Generic method to set the value of a property using expressions/lambda
- .NET 4 Code Contracts: "requires unproven: source != null"
- C#: Add conditional generic method (different generic restriction) within generic class
- Generic extension method with custom return type
- A generic filter method for Linq-EF queries
- C# generic method value
- creating Linq to sqlite dbml from DbLinq source code
- Generic Extension method for LINQ JOIN using 2 columns
- Generic Linq Find method for Repository
- LINQ operater Where not supporting any of the members when used inside generic method
- Generic All Controls Method
- Construct a Linq Expression from a generic method
- Extension method with optional generic argument
More Query from same tag
- How to turn a SQL Query Into Linq? "People who viewed this product also viewed this product."
- SQL to LINQ Conversion in C#
- Why does myDataTable.AsEnumerable().DefaultIfEmpty(myDataTable.NewRow()).First(...) NOT return myDataTable.NewRow() when .First(...) is empty?
- Each Property-Value in a MyObject-list must be unique
- Querying A Datable Using Linq Returning Distinct Values
- How to find Sum of DateTime using LINQ
- Subquery using LINQ to SQL
- MongoDB push to nested array using Linq expressions
- what is node name of element without any html tag?
- Passing a value, retrieved from a linq statement in a view, to its controller
- LINQ join with multiple conditions of different kind
- Solution for AND/OR scenario with Linq possible?
- OrderBy().ThenBy().ThenBy() not giving expected result on a List of entities
- how to clone/copy a datatable with only first n columns using linq
- Cannot insert the value NULL into column 'ID'
- Remove duplicates from DataTable and custom IEqualityComparer<DataRow>
- if control in linq?
- linq (to nHibernate): 'like in' operator
- Finding Consecutive Items in List using Linq
- Entity Framework, LINQ Query
- Updating multiple rows Linq vs SQL
- What is C# Linq "join" equivalent in rust?
- read xml file with multiple elements to a list in asp.net c#
- Static expression as instance-property for dynamic linq-queries
- LINQ merging multiple lists
- ASP.NET Entity Linq
- Still get repeated strings when using 'Distinct()'
- Querying XML attributes using LINQ
- linq: what is the expression tree syntax for cross join
- Issue with C# inheritance when using Generics and 'new' modifier to hide a parent's member