I have an IEnumerable<IEnumerable<T>>
collection that I want to convert to a single dimension collection. Is it possible to achieve this with a generic extension method? Right now I'm doing this to achieve it.
List<string> filteredCombinations = new List<string>();
//For each collection in the combinated results collection
foreach (var combinatedValues in combinatedResults)
{
List<string> subCombinations = new List<string>();
//For each value in the combination collection
foreach (var value in combinatedValues)
{
if (value > 0)
{
subCombinations.Add(value.ToString());
}
}
if (subCombinations.Count > 0)
{
filteredCombinations.Add(String.Join(",",subCombinations.ToArray()));
}
}
If it's not possible to get a generic solution, how can I optimize this in an elegant fashioned way.
IEnumerable<T> is the base interface for collections in the System. Collections. Generic namespace such as List<T>, Dictionary<TKey,TValue>, and Stack<T> and other generic collections such as ObservableCollection<T> and ConcurrentStack<T>.
IEnumerable is an interface defining a single method GetEnumerator() that returns an IEnumerator interface. It is the base interface for all non-generic collections that can be enumerated. This works for read-only access to a collection that implements that IEnumerable can be used with a foreach statement.
You cannot, because IEnumerable<T> does not necessarily represent a collection to which items can be added. In fact, it does not necessarily represent a collection at all!
IEnumerable will execute select query on server side, load data in-memory on client side and then filter data. IEnumerable can be used for querying data from in-memory collections like List, Array etc.
You can use the Enumerable.SelectMany extension method for this.
If I read your code correctly, the code for that would be:
var filteredCombinations = combinatedResults.SelectMany(o => o)
.Where(value => value > 0)
.Select(v => v.ToString());
Edit: As commented, the above code is not joining each element of the subsets to a string, as the original code does. Using the built-in methods, you can do that using:
var filteredCombinations = combinatedResults
.Where(resultSet => resultSet.Any(value => value > 0)
.Select(resultSet => String.Join(",",
resultSet.Where(value => value > 0)
.Select(v => v.ToString()).ToArray()));
Here you go:
var strings = combinedResults.Select
(
c => c.Where(i => i > 0)
.Select(i => i.ToString())
).Where(s => s.Any())
.Select(s => String.Join(",", s.ToArray());
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