How to create LINQ condition with an int Array? [duplicate] - c#

This question already has answers here:
Intersect two arrays
(2 answers)
Closed 5 months ago.
I've got 2 arrays of Int, and I want to keep only elements from second array that contains the first array elements.
int [] first = new int[2] { 1, 2};
int [] second = new int[5] { 99, 1, 2, 97, 95};
I have tried something like below.
foreach(int x in first){
second.Where(s=>s==x);
}
But it doesn't help me because I need to compare both elements from first array
second.Where(s=>s==x[0] && s[1])
and if the int is bigger I need. Do you have any ideas how to get below code line?
second.Where(s=>s==x[0] && s== x[1] && ... && s==x[n])

var elements = second.Where(first.Contains);
Maybe materialize it with a .ToList() or ToArray() call.
If the first list is really large, you could think about a faster version than the .Contains method, but for your lists, it would be overkill.

var firstSet = first.ToHashSet();
var result = second.Where(x => firstSet.Contains(x)).ToArray();

Related

Flatten jagged array and map indexes [duplicate]

This question already has answers here:
Convert 2 dimensional array
(4 answers)
Closed 7 years ago.
Is there an elegant way to flatten a 2D array in C# (using Linq or not)?
E.g. suppose
var my2dArray = new int[][] {
new int[] {1,2,3},
new int[] {4,5,6}
};
I want to call something like
my2dArray.flatten()
which would yield
{1,2,3,4,5,6}
Any ideas?
You can use SelectMany
var flat = my2dArray.SelectMany(a => a).ToArray();
This will work with a jagged array like in your example, but not with a 2D array like
var my2dArray = new [,] { { 1, 2, 3 }, { 1, 2, 3 } };
But in that case you can iterate the values like this
foreach(var item in my2dArray)
Console.WriteLine(item);

Looking to sort array from smallest to largest remove duplicates [duplicate]

This question already has answers here:
How do I remove duplicates from a C# array?
(28 answers)
Closed 5 years ago.
As the title says, I'm taking a free online course in C# and I've been stuck on this question for a bit. It's asking to write function with an array that sorts from smallest to largest and removes duplicate entries. The course has gone over arrays and sorting, but not how to remove duplicates so far. If you could help with this I'd appreciate it greatly.
There are a couple of ways to accomplish the task at hand, However, the quickest way is probably using Linq:
int[] array = { 3, 5, 1, -9, 4, 8, 23, -657, 54 };
array = array.Distinct().OrderBy(x => x).ToArray();
While there may be some more efficient methods, to help you understand the concepts a bit more, here's a simple technique.
You'll need to keep track of what entries you've already seen. Create a new list, and add the first number in the array to it. Then, take the second number in the array, and compare it to every number in your list. If it ever shows up in this list, it's a duplicate, so you can skip this number and move to the next element in the array.
ArrayList list = new ArrayList();
for (int i = 0; i < yourUnsortedArray.length; ++i) {
bool hasDuplicate = false;
for (int entry in list ) {
if (yourUnsortedArray[i] == entry) {
hasDuplicate = true;
break;
}
}
if (hasDuplicate == false) {
list.Add(yourUnsortedArray[i]);
}
}
//list will have no duplicates here.
Bonus optimization: It will help if you sort the array first. This way, you only ever have to look at the most recently added number in your list, instead of walking down the entire list every single time.
ArrayList list = new ArrayList();
for (int i = 0; i < yourSortedArray.length; ++i) {
if (list.length == 0 || list[list.length - 1] != yourSortedArray[i]) {
list.Add(yourSortedArray[i]);
}
}

Is there an "AllIndexesOf" method? [duplicate]

This question already has answers here:
Getting a collection of index values using a LINQ query
(6 answers)
Closed 9 years ago.
Background:
I'm working on an evaluator (I know there's solutions available, but I need some features that I need to implement myself). I need to find all occurrences of open brackets in the evaluation. However, for that I need all the indexes of the brackets.
Question:
Is there something like an AllIndexesOf method that returns a int[], or IEnumerable<int>?
There is not but you can get all the indexes using the following LINQ query.
int number = 10;
int[] intArray = new[] { 1, 32, 10, 5, 65, 6, 10, 10 };
var allIndexes = intArray.Select((r,i)=> new {value = r, index = i})
.Where(r=> r.value == number)
.Select(r=> r.index);
allIndexes will contain 2,6 and 7
You also can use Enumerable.Range
var indexes = Enumerable.Range(0, list.Count)
.Where(index => list[index] == yourValue);

How to delete duplicate values in an array? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Remove duplicates from array
I have an int array which contains a defined number of elements, all positive. I want to get an array from this one where all the elements appear only once. e.g. If the first array was something like {2000,2011,2011,2012,2009,2009,2000}, I want to get this {2000,2011,2012,2009}. How can I do this? I tried lots of things with for loops but I can't manage to do something good.
With LINQ it's easy:
var intArray = new[] { 2000, 2011, 2011, 2012, 2009, 2009, 2000 };
var uniqueArray = intArray.Distinct().ToArray();
http://msdn.microsoft.com/en-us/library/system.linq.enumerable.distinct.aspx
Another way is using Enumerable.GroupBy:
uniqueArray = intArray.GroupBy(i => i).Select(grp => grp.Key).ToArray();
you can do the below
var yourArray = yourArray.Distinct().ToArray();
http://msdn.microsoft.com/en-us/library/system.linq.enumerable.distinct.aspx
Alternative way:
int[] _array = new int[] {1, 2, 1,2}
var myArray = new System.Collections.ArrayList();
foreach(var item in _array){
if (!myArray.Contains(item))
myArray.Add(item);
}
In addition to the other answers, you may want to look at a HashSet, especially if you know ahead of time you will have duplicate values.

Easier way to populate a list with integers in .NET [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Populating a list of integers in .NET
Is there a simpler or more elegant way of initializing a list of integers in C# other than this?
List<int> numberList = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
or
for(int i = 1; i <= 10; i++)
{
numberList.Add(i);
}
It just doesn't seem very practical - especially if the list was to contain a large number of values. Would a loop be a more practical solution?
Thanks,
CC
You can take advantage of the Enumerable.Range() method:
var numberList = Enumerable.Range(1, 10).ToList();
The first parameter is the integer to start at and the second parameter is how many sequential integers to include.
If your initialization list is as simple as a consecutive sequence of values from from to end, you can just say
var numbers = Enumerable.Range(from, end - from + 1)
.ToList();
If your initialization list is something a little more intricate that can be defined by a mapping f from int to int, you can say
var numbers = Enumerable.Range(from, end - from + 1)
.Select(n => f(n))
.ToList();
For example:
var primes = Enumerable.Range(1, 10)
.Select(n => Prime(n))
.ToList();
would generate the first ten primes assuming that Prime is a Func<int, int> that takes an int n and returns the nth prime.

Categories