Skip to content

Sweet lambda trick to append to MVC SelectList()

Hey Ya’ll,

Well I was thinking of an ill-tricky way to append a string to the beginning of each list item in ASP.NET MVC’s SelectList collection, after thinking:

new SelectList(ViewData.Model.Formats.ForEach(x => x.Name = index + " - " + x.Name), "ID", "Name");

pausing (doh! – and not to mention not knowing how I would have gotten index incrementing..)
Argument type ‘void’ is not assignable to parameter type ‘System.Collections.IEnumerable

and then thinking again (erm. With help from some buddies over at Stack Overflow)..
I ended up with a method that was exactly what I needed! This is a sweet use of anonymous methods I find. I’m sure this approach will come in handy for a lot of things in the future; hardly ever use lambda Select()!

new SelectList(ViewData.Model.MessageTypeFieldFormats.Select((x, i) => new { ID = x.ID, Name = (i + 1) + " - " + x.Name })

This produces the desired output as…


1 – first entry
2 – second entry
3 – third entry

and so on…. have a nice day =:)

VN:F [1.8.3_1051]
Rating: 2.8/5 (2 votes cast)
VN:F [1.8.3_1051]
Rating: 0 (from 0 votes)
Sweet lambda trick to append to MVC SelectList()2.852
Bookmark and Share
kick it on DotNetKicks.com
Shout it

NOW, FOR A WORD FROM OUR SPONSORS

2 Trackbacks/Pingbacks

  1. ASP.NET MVC Archived Blog Posts, Page 1 on 10-Jan-09 at 2:37 pm

    [...] to VoteSweet lambda trick to append to MVC SelectList() (1/8/2009)Thursday, January 08, 2009 from Graham O’NealeHey Ya’ll, Well I was thinking of an ill-tricky way [...]

  2. DotNetShoutout on 05-Feb-09 at 10:16 am

    Sweet lambda trick to append to MVC SelectList() « {Programming} & Life…

    Thank you for submitting this cool story – Trackback from DotNetShoutout…

    UN:F [1.8.3_1051]
    Rating: 5.0/5 (1 vote cast)
    UN:F [1.8.3_1051]
    Rating: 0 (from 0 votes)

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*
My name is Graham O'Neale and I'm a software architect from Gold Coast, Australia. I am an overtime thinker, full time coder and awake part time in the real world. I have a keen interest in software development, particularly in the realm of programming (C#, ASP.NET, ASP.NET MVC, LINQ (2 SQL), Entity Framework, Silverlight, Blend, WCF, WPF) and a keen interest in the cutting edge and innovation. I have a new found love for design patterns, ALT.NET practices and well crafted software architecture. The purpose of this blog is to express any thoughts, findings, tips and gripes along my travels in the wonderful world of coding and technology...