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?
To find the duplicate values only:var duplicates = list. GroupBy(x => x. Key).
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With