Does there exist a LINQ method to group a given collection into subgroups with specified number of elements I mean, something like Scala's grouped method.
e.g. in Scala, List(89, 67, 34, 11, 34).grouped(2) gives List(List(89, 67), List(34, 11), List(34)).
In case such a method doesn't exist, what would be the LINQ way to do it?
Yes, you can. But you can argue if it's very pretty...
Int64[] aValues = new Int64[] { 1, 2, 3, 4, 5, 6 };
var result = aValues
.Select( ( x, y ) => new KeyValuePair<Int64, Int32>( x, y ) )
.GroupBy( x => x.Value / 2 )
.Select( x => x.Select( y => y.Key ).ToList() ).ToList();
How it works:
Select x and y from the original collection, where x is the actual value and y is the index of it in the given collection. Then group by integer devision of the index and the desired grouping length ( in this example 2 ).
Grouping by integer devision will round up to the lower - so 0 / 2 = 0, 1 / 2 = 0, etc. which will give us the needed grouping category value. This is what we are grouping against here.
For result select only the values grouped in lists and return them as a collection of lists.
Here is a website that seems to have some sample code to do what you want:
http://www.chinhdo.com/20080515/chunking/
So what you could do is take this method and create an extension method.
Extension method sample:
static class ListExtension
{
public static List<List<T>> BreakIntoChunks<T>(this List<T> list, int chunkSize)
{
if (chunkSize <= 0)
{
throw new ArgumentException("chunkSize must be greater than 0.");
}
List<List<T>> retVal = new List<List<T>>();
while (list.Count > 0)
{
int count = list.Count > chunkSize ? chunkSize : list.Count;
retVal.Add(list.GetRange(0, count));
list.RemoveRange(0, count);
}
return retVal;
}
}
You could try the approach shown in this answer to this similar question.
public static class GroupingExtension
{
public static IEnumerable<IEnumerable<T>> Grouped<T>(
this IEnumerable<T> input,
int groupCount)
{
if (input == null) throw new ArgumentException("input");
if (groupCount < 1) throw new ArgumentException("groupCount");
IEnumerator<T> e = input.GetEnumerator();
while (true)
{
List<T> l = new List<T>();
for (int n = 0; n < groupCount; ++n)
{
if (!e.MoveNext())
{
if (n != 0)
{
yield return l;
}
yield break;
}
l.Add(e.Current);
}
yield return l;
}
}
}
Use like this:
List<int> l = new List<int>{89, 67, 34, 11, 34};
foreach (IEnumerable<int> group in l.Grouped(2)) {
string s = string.Join(", ", group.Select(x => x.ToString()).ToArray());
Console.WriteLine(s);
}
Result:
89, 67
34, 11
34
Related
Im working from the Q https://www.testdome.com/for-developers/solve-question/10282
Write a function that, given a list and a target sum, returns zero-based indices of any two distinct elements whose sum is equal to the target sum. If there are no such elements, the function should return null.
For example, FindTwoSum(new List<int>() { 1, 3, 5, 7, 9 }, 12) should return a Tuple<int, int> containing any of the following pairs of indices:
1 and 4 (3 + 9 = 12)
2 and 3 (5 + 7 = 12)
3 and 2 (7 + 5 = 12)
4 and 1 (9 + 3 = 12)
So far iv got:
class TwoSum
{
public static Tuple<int, int> FindTwoSum(IList<int> list, int sum)
{
//throw new NotImplementedException("Waiting to be implemented.");
IList<int> duplicateList = list;
foreach (int i in list)
{
foreach (int j in duplicateList)
{
if (i != j)
{
if (i + j == sum)
{
return Tuple.Create(i, j);
}
}
}
}
return null;
}
public static void Main(string[] args)
{
Tuple<int, int> indices = FindTwoSum(new List<int>() { 1, 3, 5, 7, 9 }, 12);
Console.WriteLine(indices.Item1 + " " + indices.Item2);
}
}
This returns the correct answer in my code but is failing 3 out of 4 cases in the quesitong because:
Example case: Wrong answer
No solution: Correct answer
One solution: Wrong answer
Performance test with a large number of elements: Wrong answer
Ive looked at the hints
Hint 1: Nested for loops can iterate over the list and calculate a sum in O(N^2) time.
Hint 2: A dictionary can be used to store pre-calculated values, this may allow a solution with O(N) complexity.
So im using nested loops but Im guessing in this instance in order to pass hint2 I need to use a dictionary...How can I refactor this into using a dictionary?
Thanks for any help!
You are not returning indexes, you are returning values. for loops are not foreach loops.
A nested for loops solution would be something like this:
for(int i=0; i<list.Count-1; i++)
{
for(int j=i+1;j<list.Count;j++)
{
if(list[i]+list[j] == sum)
{
return Tuple.Create(i, j);
}
}
}
return null;
I'll leave the dictionary solution for you to create.
Hi this one received 50%
public static Tuple<int, int> FindTwoSum(IList<int> list, int sum)
{
int n = list.Count-1;
while(n != 0)
{
for (int i = 0; i <= list.Count-1 ; i++)
{
if (list[n] + list[i] == sum)
{
return Tuple.Create(i, n);
}
}
n--;
}
return null;
}
// get list value:
var aat = (from l1 in list
from l2 in list
where l1 + l2 == 12
group new { l1, l2} by new { l1, l2 } into gp
select new {gp.Key}).ToDictionary( a => a.Key.l1, b => b.Key.l2 );
// get list index of the value:
var aav = (from l1 in list
from l2 in list
where l1 + l2 == 12
group new { l1, l2 } by new { l1, l2 } into gp
select new { gp.Key })
.ToDictionary( a => list.IndexOf(a.Key.l1), b => list.IndexOf(b.Key.l2)
);
I want to create a new group when the difference between the values in rows are greater then five.
Example:
int[] list = {5,10,15,40,45,50,70,75};
should give me 3 groups:
1,[ 5,10,15 ]
2,[40,45,50]
3,[70,75]
Is it possible to use Linq here?
Thx!
Exploiting side effects (group) is not a good practice, but can be helpful:
int[] list = { 5, 10, 15, 40, 45, 50, 70, 75 };
int step = 5;
int group = 1;
var result = list
.Select((item, index) => new {
prior = index == 0 ? item : list[index - 1],
item = item,
})
.GroupBy(pair => Math.Abs(pair.prior - pair.item) <= step ? group : ++group,
pair => pair.item);
Test:
string report = string.Join(Environment.NewLine, result
.Select(chunk => String.Format("{0}: [{1}]", chunk.Key, String.Join(", ", chunk))));
Outcome:
1: [5, 10, 15]
2: [40, 45, 50]
3: [70, 75]
Assuming collection has an indexer defined, can be something like this:
const int step = 5;
int currentGroup = 1;
var groups = list.Select((item, index) =>
{
if (index > 0 && item - step > list[index - 1])
{
currentGroup++;
}
return new {Group = currentGroup, Item = item};
}).GroupBy(i => i.Group).ToList();
In my opinion, just write a function to do it. This is easier to understand and more readable than the Linq examples given in other answers.
public static List<List<int>> Group(this IEnumerable<int> sequence, int groupDiff) {
var groups = new List<List<int>>();
List<int> currGroup = null;
int? lastItem = null;
foreach (var item in sequence) {
if (lastItem == null || item - lastItem.Value > groupDiff) {
currGroup = new List<int>{ item };
groups.Add(currGroup);
} else {
// add item to current group
currGroup.Add(item);
}
lastItem = item;
}
return groups;
}
And call it like this
List<List<int>> groups = Group(list, 5);
Assumption: list is sorted. If it is not sorted, just sort it first and use the above code.
Also: if you need groups to be an int[][] just use the Linq Method ToArray() to your liking.
I have the following list of integers that I need to extract varying lists of integers containing numbers from say 2-4 numbers in count. The code below will extract lists with only 2 numbers.
var numList = new List<int> { 5, 20, 1, 7, 19, 3, 15, 60, 3, 21, 57, 9 };
var selectedNums = (from n1 in numList
from n2 in numList
where (n1 > 10) && (n2 > 10)
select new { n1, n2 }).ToList();
Is there any way to build up this Linq expression dynamically so that if I wanted lists of 3 numbers it would be compiled as below, this would save me having to package the similar expression inside a different method.
var selectedNums = (from n1 in numList
from n2 in numList
from n3 in numList
where (n1 > 10) && (n2 > 10) && (n3 > 10)
select new { n1, n2, n3 }).ToList();
As with all good questions the way to solve this is with Linq and with Recursion!
public IEnumerable<IEnumerable<T>> Permutation<T>(int count, IEnumerable<T> sequence)
{
if(count == 1)
{
foreach(var i in sequence)
{
yield return new [] { i };
}
yield break;
}
foreach(var inner in Permutation(count - 1, sequence))
foreach(var i in sequence)
{
yield return inner.Concat(new [] { i });
}
}
var foo = Permutation<int>(3, numList.Where(x => x > 10));
[Edited]
You can combine joins and where clauses with loops and conditions, like that:
var q = numList.Where(x => x > 10).Select(x => new List<int>{ x });
for(i = 1; i <= numToTake; ++i)
q = q.Join(numList.Where(x => x > 10), x=> 0, y => 0, (x, y) => { x.Add(y); return x; });
(that returns a List instead of an anonymous object)
Edit 2: Thanks Aron for the comment.
I am not sure if it can help you but an idea how I achieved the same dynamic result based on condition.
var q=(from n in context.TableName
.......);
if(x!=null) //this can be the condition (you can have yours)
var final=q.Select(i=>i....); //I am using q again here
I am not sure what will be the performance.
I have a collection uni-dimensional like this:
[1,2,4,5.....n]
I would like to convert that collection in a bi-dimensional collection like this:
[[1,2,3],
[4,5,6],
...]
Basically I want to group or split if you want, the array in groups of 'n' members
I can do it with a foreach statement, but I am currently learning LINQ so instead of iterating through all elements and create a new array manually I would like to use the LINQ features (if applicable)
Is there any LINQ function to help me to accomplish this??
I was thinking in the GroupBy or SelectMany I do not know if they will help me though but they might
Any help will be truly appreciate it =) :**
You can group by the index divided by the batch size, like this:
var batchSize = 3;
var batched = orig
.Select((Value, Index) => new {Value, Index})
.GroupBy(p => p.Index/batchSize)
.Select(g => g.Select(p => p.Value).ToList());
Use MoreLinq.Batch
var result = inputArray.Batch(n); // n -> batch size
Example
var inputs = Enumerable.Range(1,10);
var output = inputs.Batch(3);
var outputAsArray = inputs.Batch(3).Select(x=>x.ToArray()).ToArray(); //If require as array
You want Take() and Skip(). These methods will let you split an IEnumerable. Then you can use Concat() to slap them together again.
The sample below will split an array into groups of 4 items each.
int[] items = Enumerable.Range(1, 20).ToArray(); // Generate a test array to split
int[][] groupedItems = items
.Select((item, index) => index % 4 == 0 ? items.Skip(index).Take(4).ToArray() : null)
.Where(group => group != null)
.ToArray();
It's not a pure LINQ but it's intended to be used with it:
public static class MyEnumerableExtensions
{
public static IEnumerable<T[]> Split<T>(this IEnumerable<T> source, int size)
{
if (source == null)
{
throw new ArgumentNullException("source can't be null.");
}
if (size == 0)
{
throw new ArgumentOutOfRangeException("Chunk size can't be 0.");
}
List<T> result = new List<T>(size);
foreach (T x in source)
{
result.Add(x);
if (result.Count == size)
{
yield return result.ToArray();
result = new List<T>(size);
}
}
}
}
It can be used from your code as:
private void Test()
{
// Here's your original sequence
IEnumerable<int> seq = new[] { 1, 2, 3, 4, 5, 6 };
// Here's the result of splitting into chunks of some length
// (here's the chunks length equals 3).
// You can manipulate with this sequence further,
// like filtering or joining e.t.c.
var splitted = seq.Split(3);
}
It's as simple as:
static class LinqExtensions
{
public static IEnumerable<IEnumerable<T>> ToPages<T>(this IEnumerable<T> elements, int pageSize)
{
if (elements == null)
throw new ArgumentNullException("elements");
if (pageSize <= 0)
throw new ArgumentOutOfRangeException("pageSize","Must be greater than 0!");
int i = 0;
var paged = elements.GroupBy(p => i++ / pageSize);
return paged;
}
}
I based my solution of Jeremy Holovacs's answer and used Take() and Skip() to create subarrays.
const int batchSize = 3;
int[] array = new int[] { 1,2,4,5.....n};
var subArrays = from index in Enumerable.Range(0, array.Length / batchSize + 1)
select array.Skip(index * batchSize).Take(batchSize);
Starting with .NET 6, there is the System.Linq.Enumerable.Chunk(this IEnumerable<TSource>, int size) extension method. It returns an IEnumerable<TSource[]> where each item is an array of size elements, except the last item, which could have fewer.
Code like this:
using System;
using System.Collections.Generic;
using System.Linq;
int[] input = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
IEnumerable<int[]> chunks = input.Chunk(3);
foreach (int[] chunk in chunks)
{
foreach (int i in chunk)
{
Console.Write($"{i} ");
}
Console.WriteLine();
}
outputs
1 2 3
4 5 6
7 8 9
10
I want to create an extension method like this
public static bool AllConsecutives(this IEnumerable<int> intValues )
This method should return true if all items in the list are consecutive (with no gaps)
some test cases
(new List<int>() {2, 3, 4, 5, 6}).AllConsecutives() == true
(new List<int>() {3, 7, 4, 5, 6}).AllConsecutives() == true //as it is not sensitive to list order
(new List<int>() {2, 3, 4, 7, 6}).AllConsecutives() == false //as the five is missing
int expected = intValues.Min();
foreach(int actual in intValues.OrderBy(x => x))
{
if (actual != expected++)
return false;
}
return true;
You can also verify, that collection has at least one item, before executing Min. Or you can sort items prior to taking min (in this case it will be first one, or will not be any, if collection is empty). Also in this case you will save one iteration for finding minimal value:
var sortedValues = intValues.OrderBy(x => x);
int expected = sortedValues.FirstOrDefault();
foreach (int actual in sortedValues)
{
if (actual != expected++)
return false;
}
return true;
Tried and seems to work with the given examples
public static bool AllConsecutives(this IEnumerable<int> intValues )
{
var ord = intValues.OrderBy(i => i);
int curV = ord.Min();
foreach(int x in ord)
{
if(x != curV)
return false;
curV++;
}
return true;
}
The list is consecutive if it does not contains duplicates and the difference between the max. and min. values is equal to the number of items in the list minus one, so:
public static bool AllConsecutives(this IEnumerable<int> intValues)
{
int minValue = Int32.MaxValue;
int maxValue = Int32.MinValue;
int count = 0;
HashSet<int> values = new HashSet<int>();
foreach (int intValue in intValues) {
if (values.Contains(intValue))
return false;
values.Add(intValue);
if (intValue > maxValue)
maxValue = intValue;
if (intValue < minValue)
minValue = intValue;
count++;
}
return (count == 0) || (maxValue-minValue+1 == count);
}
Error checking and using Linq:
public static class myExtension
{
public static bool AllConsecutives(this IEnumerable<int> targetList)
{
bool result = false;
if ((targetList != null) && (targetList.Any ()))
{
var ordered = targetList.OrderBy (l => l);
int first = ordered.First ();
result = ordered.All (item => item == first++);
}
return result;
}
}
// tested with
void Main()
{
Console.WriteLine ( (new List<int>() {2, 3, 4, 5, 6}).AllConsecutives() ); // true
Console.WriteLine ( (new List<int>() {3, 7, 4, 5, 6}).AllConsecutives() ); // true //as it is not sensitive to list order
Console.WriteLine ( (new List<int>() {2, 3, 4, 7, 6}).AllConsecutives() ); // false //as the five is missing
}
Something like this:
if (intValues.Count() <= 1)
return true;
var ordered = intValues.OrderBy(i => i).ToList();
return (ordered.First() + ordered.Count() - 1) == ordered.Last();
list.Sort();
return !list.Skip(1).Where((i, j) => (i != (list[j] + 1))).Any();
Another possible solution that doesn't requires sorting, is to use hashset, and while building the hashset you can hold the min value. With this the run time will be O(n).
This will not take care of duplicate values which you can just add a check while building the hashset and see if the hashset already contains the value.
HashSet<int> hash = new HashSet<int>();
int minValue = int.MaxValue;
foreach(int i in list)
{
if(minValue > i)
minValue = i;
hash.Add(i);
}
for(int count = 1; count < list.Count; ++count)
{
if(!hash.Contains(++minValue))
return false;
}
return true;