Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ query to create a collection of objects combined from a collection of strings [duplicate]

Tags:

c#

.net

linq

Is it possible with single LINQ query to convert a single dimensional array like this:

string[] source = new string[] { "1", "Name1", "Value1", "2", "Name2", "Value2", "3", "Name3", "Value3" };

into IEnumerable<> of three objects containing three properties, build from each three successive strings?

like image 426
Konrad Kokosa Avatar asked Nov 17 '13 11:11

Konrad Kokosa


People also ask

How do I find duplicate records in LINQ?

To find the duplicate values only:var duplicates = list. GroupBy(x => x. Key).

What types of objects can you query using LINQ?

You can use LINQ to query any enumerable collections such as List<T>, Array, or Dictionary<TKey,TValue>. The collection may be user-defined or may be returned by a . NET API. In a basic sense, LINQ to Objects represents a new approach to collections.

What is SelectMany in LINQ C#?

The SelectMany in LINQ is used to project each element of a sequence to an IEnumerable<T> and then flatten the resulting sequences into one sequence. That means the SelectMany operator combines the records from a sequence of results and then converts it into one result.

What is any () in LINQ?

The Any operator is used to check whether any element in the sequence or collection satisfy the given condition. If one or more element satisfies the given condition, then it will return true. If any element does not satisfy the given condition, then it will return false.


1 Answers

Yes, it's possible, you could group them by the index in the array:

string[] source = new string[] { "1", "Name1", "Value1", "2", "Name2", "Value2", "3", "Name3", "Value3" };
var result = source
    .Select((element, index) => new { element, index })
    .GroupBy(x => x.index / 3)
    .Select(x => new
    {
        Id = x.ElementAt(0).element,
        Name = x.ElementAt(1).element,
        Value = x.ElementAt(2).element
    }).ToList();

// at this stage the result variable will represent a list of 3 elements where
// each element is an anonymous object containing the 3 properties. You could of course
// replace the anonymous object with a model if you intend to use the result of the query
// outside of the scope of the method it is being executed in.

Obviously in this example, there's no error checking. It is something you might consider doing before running the LINQ query. The length of the array should be divisible by 3 obviously.

like image 141
Darin Dimitrov Avatar answered Sep 27 '22 21:09

Darin Dimitrov