tags:

views:

51

answers:

2

How do I return a top 5 with rank number using linq?

Dim Top5 = From A In DAO.Cache.Select(Of VO.Empresa).Take(5) Select A.Nome

I would like this result:

Rank  Name
1     "Example Name"
2     "Example Name"
3     "Example Name"
4     "Example Name"
5     "Example Name"
+1  A: 

You need to use the Select overload which provides the index:

Dim Top5 = DAO.Cache.Take(5).Select(Function(A, Index) New With { .Rank = Index, .Name = A.Nome })

(I kept the property spelling .Nome - though I suspect it may need to be .Name)

Reed Copsey
Thanks Reed, it worked perfectly!
Fernando
By the way, in Brazil, "name" is "nome", with "o". =)
Fernando
@Fernando: Yeah - I wasn't sure, though, since you used "Name" everywhere except once place, where you used "Nome" - I left it in, knowing "Nome" is correct in some places, just in case ;)
Reed Copsey
A: 

I'm not entirely sure I understand your question entirely: but I'm assuming you want to order your list to produce the top 5 in Rank - ascending order?

You can quite easily do this with the built in LINQ ordering syntax:

VB: Dim Top5 = From o in objects Order By o.Rank Ascending Select o

C#: var top5 = from o in objects orderby o.Rank ascending select o

(surprising similar in this case /giggle)

For example, you could do the following:

C#:

void Main()
{
    List<MyObject> objs = new List<MyObject>();
    objs.Add(new MyObject{ Rank = 1, Message = "NUMBER ONE"});
    objs.Add(new MyObject{ Rank = 3, Message = "NUMBER THREE"});
    objs.Add(new MyObject{ Rank = 5, Message = "NUMBER FIVE"});
    objs.Add(new MyObject{ Rank = 4, Message = "NUMBER FOUR"});
    objs.Add(new MyObject{ Rank = 2, Message = "NUMBER TWO"});

    var sortedobjs = from o in objs
                     orderby o.Rank ascending
                     select o;
    Console.WriteLine(sortedobjs.ToList());
}

public class MyObject
{
    public int Rank {get; set;}
    public string Message {get; set;}
}

Which would spit out:

Rank  Message
1     NUMBER ONE
2     NUMBER TWO
3     NUMBER THREE
4     NUMBER FOUR
5     NUMBER FIVE

HTH.

Daniel May