Wednesday, November 16, 2011

LINQ statement returns rownumber / Line Number Into Linq Query Results

Scenario:
data:
First
Second
Third
I like to display it as:
1. First
2. Second
3. Third
Solutions:
 

var list = new List<string>{
"First","Second","third"
};
var query = (from s in list
select s)
.Select((obj, index) => index + ". " + obj);

foreach (string s in query)
Console.WriteLine(s);


2.



static void Main(string[] args)
{
string[] nums = {"One","Two", "Three"};

int X = 0;
var q = (from a in nums select new {ID = IncrementX(ref X), num = a});

foreach (var a in q)
{
Console.WriteLine (a.ID.ToString() + ", " + a.num);
}
Console.ReadLine();
}

static int IncrementX(ref int X)
{
X+=1;
return X;
}




Example:





var query = from s in entities.Scores
where s.Game.Id == guid
orderby s.PlayerScore descending
select new
{
PlayerName = s.PlayerName,
PlayerScore = s.PlayerScore
};

var list = query.AsEnumerable()
.Select((player, index) => new ScoreWithRank()
{
PlayerName = player.PlayerName,
PlayerScore = player.PlayerScore,
Rank = index + 1;
}
.ToList();
listBox.ItemsSource = list.Select((player, index) => new
{
PlayerName = player.PlayerName,
PlayerScore = player.PlayerScore,
Rank = index+=1
}).ToList();

No comments :

Post a Comment