A (very) Interesting LINQQuery

I was reading ASP .NET forums when I found this post :

The scenario is :

We have input data in this format :

EmpId Name wages
1 Bilal $200
1 Bilal $300
1 Bilal $400
2 Haris $500
2 Haris $600

The required output is in following way:
Name OriginalWage DuplicateWage
Tom $200 $300
Tom $200 $400
Rob $500 $600

We need to combine each person first record to all other records using LINQ. So I decided to write my own solution of this problem.

I created this sample input data:
For sample input data in c#:
var ret = new[]{
new { SNO=1,Name="Tom",Wages=200 },
new { SNO=1,Name="Tom",Wages=300 },
new { SNO=1,Name="Tom",Wages=400 },
new { SNO=2,Name="Rob",Wages=500 },
new { SNO=2,Name="Rob",Wages=600 },
new { SNO=3,Name="John",Wages=700 },
new { SNO=3,Name="John",Wages=800 },
new { SNO=3,Name="John",Wages=500 },
new { SNO=3,Name="John",Wages=600 }

To achieve the results as per our requirment, i wrote this LINQ query:

var mylinqquery= (from item in result
group item by item.empid into group
let one = group.First()
let second = group.Skip(1).Select(x => new { Name = emp.Name, Wage = emp.Wages, Dup =x.Wages})
select second).SelectMany(x=>x).ToList();

Here is our desired output:



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s