score:1
I'm really not sure this is much better than your original, but for the purpose of another solution the general process is
- Use
Select
to project a list working out a grouping - Use
GroupBy
to group by the above - Use
Select
again to project the grouped items to an array ofItem
- Use
ToList
to project the result to a list
public static List<Item[]> GetContiguousSequences2(Item []items)
{
var currIdx = 1;
return items.Select( (item,index) => new {
item = item,
index = index == 0 || items[index-1].Stop == item.Start ? currIdx : ++currIdx
})
.GroupBy(x => x.index, x => x.item)
.Select(x => x.ToArray())
.ToList();
}
Live example: https://dotnetfiddle.net/mBfHru
Another way is to do an aggregation using Aggregate
. This means maintaining a final Result
list and a Curr
list where you can aggregate your sequences, adding them to the Result
list as you find discontinuities. This method looks a little closer to your original
public static List<Item[]> GetContiguousSequences3(Item []items)
{
var res = items.Aggregate(new {Result = new List<Item[]>(), Curr = new List<Item>()}, (agg, item) => {
if(!agg.Curr.Any() || agg.Curr.Last().Stop == item.Start) {
agg.Curr.Add(item);
} else {
agg.Result.Add(agg.Curr.ToArray());
agg.Curr.Clear();
agg.Curr.Add(item);
}
return agg;
});
res.Result.Add(res.Curr.ToArray()); // Remember to add the last group
return res.Result;
}
Live example: https://dotnetfiddle.net/HL0VyJ
score:0
Your solution is okay. I don't think that LINQ adds any simplification or clarity in this situation. Here is a fast solution that I find intuitive:
static List<Item[]> GetContiguousSequences(Item[] items)
{
var result = new List<Item[]>();
int start = 0;
while (start < items.Length) {
int end = start + 1;
while (end < items.Length && items[end].Start == items[end - 1].Stop) {
end++;
}
int len = end - start;
var a = new Item[len];
Array.Copy(items, start, a, 0, len);
result.Add(a);
start = end;
}
return result;
}
score:1
You can implement ContiguousSplit
as a corutine: let's loop over source
and either add item
into current
range or return it and start a new one.
private static IEnumerable<Item[]> ContiguousSplit(IEnumerable<Item> source) {
List<Item> current = new List<Item>();
foreach (var item in source) {
if (current.Count > 0 && current[current.Count - 1].Stop != item.Start) {
yield return current.ToArray();
current.Clear();
}
current.Add(item);
}
if (current.Count > 0)
yield return current.ToArray();
}
then if you want materialization
List<Item[]> GetContiguousSequences(Item []items) => ContiguousSplit(items).ToList();
Source: stackoverflow.com
Related Articles
- Split a list of objects into sub-lists of contiguous elements using LINQ?
- Using linQ to group list of object into new lists of objects
- Using Linq to group a list of objects into a new grouped list of list of objects
- Split string into list of N-length strings using LINQ
- LINQ query to split an ordered list into sublists of contiguous points by some criteria
- Using Linq to group a list of objects that contains primitives data into a new grouped list of objects
- LINQ Split list into lists by date
- Get the count of distinct elements from a list of lists using LINQ
- Converting a list of lists into a single list using linq
- Split list into two lists with single LINQ statement
- Using LINQ how to transform a List of Lists using elements index
- how split the List of strings into another Lists if particular string matches condition using linq?
- List of EF objects to Dictionary of lists using linq
- Reduce a list into smaller lists of two using LINQ (Functional Programming)
- Grouping a list of objects by parent using linq to output child elements
- Split list into sets using Linq
- How to split multi-level list of tuples into multi-level lists of values using LINQ?
- Split List into Sublist using Linq based on content of list
- Aggregating Lists inside of a List of objects using LINQ
- Split a list into multiple lists using lambda expression
- Split array or list into segments using LINQ
- Construct a list of wpf Hyperlink elements from an XML source file using Linq
- Using Linq to do: Compile a list of all lists within a list of objects
- Using Linq to group a list of objects into a new grouped list of list of objects with 4 objects in each group
- Remove set of elements from list A and add into list B using Linq
- Return select objects and only desired subvalues from a list of lists using LINQ
- Creating sub lists with objects of the same attribute from a list using LINQ
- Merging lists of objects using linq while showing preference over a condition in one list
- Using linq to instantiate objects containing lists of other objects, where query criteria is on inner list
- Split List into Sublists with LINQ
- LINQ Group By and merge properties
- Filter query by multiple parameters from the list of objects
- Converting an IQueryable<int?> to IQueryable<int> after nulls have been removed
- SQL Server Always encrypt collation incompatibility on insert
- LinQ to SQL throws Stackoverflow exception when using Any()
- DB Context - Query to select post from a category
- Display list of distinct book names from LINQ query
- How to join two tables using group by and do the calculation?
- Aggregation using LINQ
- C# - TakeWhile and SkipWhile not returning?
- The specified type member is not supported in LINQ to Entities. Using 0 to many relationship for an entity property
- Merging 2 lists in C# with a combiner lamba
- How to grasp all C# functional features?
- Sum of Values in SortedList and Condition on Keys
- Pivot Table in LINQ in VB.NET
- How to write SQL translateable linq code that groups by one property and returns distinct list
- LINQ Group By Sum how do i return null for decimal type field
- Appending results from LINQS query to paged list
- LINQ - Where Conditions - "if-else" Cases
- Unable to bind list to gridview after sorted using linq ASP.NET