How to assign a computed value to the same array back?

 Posted by Niladri.Biswas on 7/13/2012 | Category: LINQ Interview questions | Views: 1717 | Points: 40
Answer:

Consider the below input

var input = new string[] { "Apple", "Banana", "Mango", "Apple", "Orange", "Mango", "Strawberry", "Apple" };


The problem is to write a query using LINQ that will count the number of fruits and will assign back the value to the same array i.e. we should not create another array for storing the computed values.

Solution


var input = new string[] { "Apple", "Banana", "Mango", "Apple", "Orange", "Mango", "Strawberry", "Apple" };

input = (from a in input
group a by a into g
where g.Count() >= 2
select g.Key + " ( " + g.Count() + " )").ToArray();


Output
Apple ( 3 )

Mango ( 2 )


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response