What I am trying to do is loop through an integer array
int[] integerarray = { 1, 2, 3, 4 };
for (??????)
{
// What do I do here?
}
Until I get to 3. I'm not sure how though.
we can achieve this by using simple for each loop
foreach(int i in integerarray)
{
if(i==3)
{
// do your stuf here;
break;
}
}
int[] integerarray = { 1, 2, 3, 4 };
for (int i=0;i<integerarray.Length;i++)
{
if(integerarray[i]==3)
break;
//Do something here
}
One way to do a loop of a fixed number is a while loop.
int counter = 0;
while(counter < 3)
{
tmp = integerArray[counter];
????
counter++;
}
You can use linq TakeWhile method to get the elements from a sequence as long as a specified condition is true.
Here you want that return element untill we found 3 in the sequence so you can write this statement like this
var result = integerarray.TakeWhile(x => !x.Equals(3)).ToList();
result will contains the items which comes before 3
in your case result will have 1,2
Use LINQ.
int[] integerarray = { 1, 2, 3, 4 };
for (var number = integerarray.TakeWhile(x => x != 3))
{
// Do something
}
Related
I have a variable number of List-objects, of which I need to compare the values at the same indexes. The number of entries in the list is given and does not vary.
For example:
4 Lists
each 4 entries
So what I'd be looking for in this example, is 4 bools, one per index.
Getting the indexes of unmatching entries would be fine, too.
Pseudo:
bool isFirstEqual = (list1[i] == list2[i] == list3[i] == list4[i]);
But I need to do this in a fashion that's applicable for a variable number of lists. I could have 6 Lists, but also 2.
I was thinking of doing something with LINQs .Except() but am not sure how to use it with a variable number of lists.
I am struggling to find the elegant solution that I'm sure is out there.
Any help on this is appreciated.
If i understand what you mean, something like this might work
public static bool IsEqual<T>(int index, params List<T>[] ary)
{
for (var i = 1; i < ary.Length; i++)
if (!EqualityComparer<T>.Default.Equals(ary[0][index], ary[i][index]))
return false;
return true;
}
Usage
var isSecondelemEqual = IsEqual(1, list1, list2, list3,...)
Update
Basically takes a variable list of lists, and assumes you want to check the index of each list against each other.
bool AreIndexesEqual(int index, List<List<int>> lists)
{
int match = lists[0][index];
foreach(List<int> list in lists.Skip(1))
{
if (list[index] != match)
{
return false;
}
}
return true;
}
Given for example:
List<List<int>> listOfLists = new List<List<int>>
{
new List<int> { 1, 100, 2},
new List<int> { 2, 100, 3},
new List<int> { 3, 100, 4},
new List<int> { 4, 100, 5},
};
So a List<> of List<int>
the totally unreadable LINQ expression that will return a List<bool> is something like:
List<bool> result = Enumerable.Range(0, listOfLists.Count != 0 ? listOfLists[0].Count : 0)
.Select(x => listOfLists.Count <= 1 ?
true :
listOfLists.Skip(1).All(y => y[x] == listOfLists[0][x])
).ToList();
Here I want to show you that if your first solution to any problem is LINQ, then perhaps now you will have two problems.
Now... What does this linq does? We have 4 List<int>, each one with 3 elements... So 3 rows of 4 columns. We want to calculate the result "by row", so the first thing is discover the number of rows, that is listOfLists[0].Count (we put a pre-check for the case that we have 0 rows). Now we generate an index (like a for), using Enumerable.Range(0, numberofrows), like for (int i = 0; i < numberofrows; i++). For each row we see if there are 0 or 1 columns (listOfLists.Count <= 1), then the result is true, otherwise we compare all the other columns y[x] with the first column listOfLists[0][x].
With a dual for cycle it becomes clearer probably:
var result2 = new List<bool>(listOfLists.Count != 0 ? listOfLists[0].Count : 0);
// Note the use of .Capacity here. It is listOfLists.Count != 0 ? listOfLists[0].Count : 0
for (int col = 0; col < result2.Capacity; col++)
{
if (listOfLists.Count <= 1)
{
result2.Add(true);
}
else
{
bool equal = true;
for (int row = 1; row < listOfLists.Count; row++)
{
if (listOfLists[row][col] != listOfLists[0][col])
{
equal = false;
break;
}
}
result2.Add(equal);
}
}
Note that both programs can be simplified: new int[0].All(x => something) == true, so .All() on empty IEnumerable<> is true. You can remove listOfLists.Count <= 1 ? true : and if (...) { ... } else up to the else keyword, keeping only the code inside the else:
var result2 = new List<bool>(listOfLists.Count != 0 ? listOfLists[0].Count : 0);
// Note the use of .Capacity here. It is listOfLists.Count != 0 ? listOfLists[0].Count : 0
for (int col = 0; col < result2.Capacity; col++)
{
bool equal = true;
for (int row = 1; row < listOfLists.Count; row++)
{
if (listOfLists[row][col] != listOfLists[0][col])
{
equal = false;
break;
}
}
result2.Add(equal);
}
Here you go
IEnumerable<bool> CompareAll<T>(IEnumerable<IEnumerable<T>> source)
{
var lists = source.ToList();
var firstList = lists[0];
var otherLists = lists.Skip(1).ToList();
foreach(var t1 in firstList)
{
yield return otherlists.All(tn => tn.Equals(t1));
}
}
I have goggled and looked various threads at this website and I am still not getting this right.
Objective
Would like to split int arrays in 3 groups
Problem
I am getting an output...
1
4
7
instead of...
[1,2,3]
[4,5,6]
[7,8,9]
1st attempt
static void Main(string[] args)
{
int[] arraya = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Array.Sort(arraya);
int a = 0;
int divideBya = 3;
var resulta = arraya.GroupBy(s => a++ / divideBya).Select(g => g.ToArray()).ToArray();
foreach(var item in resulta)
{
Console.WriteLine("{0}", item[0]);
}
}
2nd attempt
static void Main(string[] args)
{
int u = 0;
int divideByb = 3;
IEnumerable<List<int>> groupedObjects = Enumerable.Range(1, 9).GroupBy(x => u++ / divideByb)
.Select(group => group.ToList()).ToList();
foreach (var item in groupedObjects)
{
Console.WriteLine("{0}", item[0]);
}
}
Can someone point me to the right direction?
Thanks
Your code seems almost correct. Your main problem is your output:
foreach (var item in groupedObjects)
{
Console.WriteLine("{0}", item[0]);
}
You only output the first element of each array. Try this:
foreach (var items in groupedObjects)
Console.WriteLine(string.Join(", ", items));
Try changing your writeline statement to:
Console.WriteLine($"[{item[0]},{item[1]},{item[2]}]");
Is there a way to detect similar elements within multidimensional arrays? For example:
int[][] arrayA = {{1 , 2}, {4 , 6}, {3, 7}};
int[][] arrayB = {{3 , 2}, {1 , 2}, {8, 5}};
Both arrayA and arrayB have the element {1 , 2}. (Or simply, any element in common) Is there a way to detect that it's true?
Yes, you just need to code the logic and you can detect.
bool result = false;
foreach (var arrayAItem in arrayA)
{
foreach (var arrayBItem in arrayB)
{
if (arrayAItem.SequenceEqual(arrayBItem))
{
result = true;
break;
}
}
if (result == true)
{
break;
}
}
and a one liner
bool result = arrayA.Any(arrayAItem => arrayB.Any(arrayBItem => arrayAItem.SequenceEqual(arrayBItem)));
It's hard to give you the answer without just feeding you code, but:
For each element in Array A, check if it's equal to each element in Array B. So basically, you'd need a nested foreach. If you want to record which elements they have in common, add them to a List<ElementType> (not an array since you want to dynamically populate it).
It's not quite that simple since your arrays are nested. You can't just check arrayA[x] == arrayB[x] because you'd be comparing arrays, which are reference types (it would return false unless they both pointed to the same piece of memory). Instead, you'll have to add one more loop inside of the two foreaches you already have to check each int in arrayA against the correlating one in arrayB. int is a value type, so an == comparison would behave how you'd expect it to.
Here is how you can do this (and not only):
var commonItems = from innerA in arrayA
from innerB in arrayB
where innerA.SequenceEqual(innerB)
select innerA;
bool anyCommon = commonItems.Any();
var firstCommon = commonItems.FirstOrDefault();
var commonCount = commonItems.Count();
I guess the variable names are self explanatory :-)
Something along this?
arrayA.Where(arr => arrayB.Any(arr2 => arr1.OrderBy(x => x)
.SequenceEquals(arr.OrderBy(x => x)))).ToArray()
You can remove the two OrderBy calls if you want, depending on how you wish to consider two arrays "the same".
The following code becomes lengthened, but will give you the output you want:
private void TestArrays()
{
int[,] arrayA = new[,] { { 1, 2 }, { 4, 6 }, { 3, 7 } };
int[,] arrayB = new[,] { { 3, 2 }, { 1, 2 }, { 8, 5 } };
int parentLengthA = arrayA.GetLength(0);
int childLengthA = arrayA.GetLength(1);
int parentLengthB = arrayB.GetLength(0);
int childLengthB = arrayB.GetLength(1);
int[] itemsOfA;
int[] itemsOfB;
List<int[]> matchedArrays = new List<int[]>();
for (int i = 0; i < parentLengthA; i++)
{
itemsOfA = new int[childLengthA];
for (int j = 0; j < parentLengthB; j++)
{
itemsOfB = new int[childLengthB];
bool isMatched = true;
if (itemsOfA.Length != itemsOfB.Length)
{
isMatched = false;
break;
}
for (int k = 0; k < itemsOfA.Length; k++)
{
if (arrayA[i, k] != arrayB[j, k])
{
isMatched = false;
break;
}
else
{
itemsOfA[k] = arrayA[i, k];
}
}
if (isMatched)
{
matchedArrays.Add(itemsOfA);
}
}
}
//Just to output the matched array(s)
if (matchedArrays.Count > 0)
{
StringBuilder sb = new StringBuilder();
foreach (int[] matchedArray in matchedArrays)
{
foreach (int i in matchedArray)
{
sb.Append(i + ",");
}
sb.AppendLine();
}
MessageBox.Show(sb.ToString());
}
}
I want to compare two array in c#. If they are matched go to if condition else go to the else condition. How can we do that in c#.
int[] numbers = new int[] { 1, 2, 3, 4, 5 };
int[] numbers2 = new int[] { 1, 2, 3, 4, 5 };
I want to compare the two arrays like
if(numbers == numbers2){
do something
}else{
do something
}
You can use the Enumerable.SequenceEqual() extension method. It does exactly what you want:
if (numbers.SequenceEqual(numbers2)) {
// do something
} else {
// do something else
}
You can create a extension function for array, which takes input another array object and then using HashSet you can compare two arrays. Like -
if (numbers.ArrayEqual(number2){
// do this
}
else{
// do that
}
function static bool ArrayEqual(this int[] a, int []b)
{
return a.Length == b.Length
&& new HashSet<string>(a).SetEquals(b);
}
Hi there is there a way to check specific integer array indexes for specific numbers in C#; for example what I would love to have worked would be:
if(si[6] || si[7] || si[8] == 3)
{
MessageBox.Show("3 detected")
}
else
{
continue();
{
Obviously this doesn't work. Is there a clean way to do this? Thank you for looking.
var indexes = new int[] {6, 7, 8};
if (indexes.Any(i => si[i] == 3))
{
MessageBox.Show("3 detected")
}
The simplest is to make three separate checks:
if (si[6] == 3 || si[7] == 3 || si[8] == 3)
You could do this a bit neater using a method with a params:
public static bool HasValue(int value, params int[] itemsToCheck)
{
bool valueDetected = false;
foreach(var item in itemsToCheck)
{
valueDetected |= item == value;
}
return valueDetected;
}
Then you could just call it like this:
if (HasValue(3, si[6], si[7], si[8]))
{
}
You can use Array.IndexOf function to find the index of the integer. If array has the integer then it will return the index else it will return -1.
Like this
int[] a = new int[] { 1, 2 };
int c = Array.IndexOf(a, 2);