I have two arrays with same length. for example
arr1 {1,2,3,4,5,6,7,8,9,0}.
arr2 {1,2,5,3,4,6,7,1,1,0}.
I need to get indexes of elements which are different:
{2,3,4,7,8}
How to do this using Linq?
The simplest I could think of:
int[] diff = Enumerable.Range(0, arr1.Length).Where(i => arr1[i] != arr2[i]).ToArray();
This should work:
int[] arr1 = new[] {1,2,3,4,5,6,7,8,9,0};
int[] arr2 = new[] {1,2,5,3,4,6,7,1,1,0};
var differentIndexes = arr2.Select((item, index) => new { item, index })
.Where(x => x.item != arr1[x.index])
.Select(x => x.index)
.ToArray();
You could use Enumerable.Zip() to walk the arrays in parallel, compare the values, then output matching sequence indices:
int [] arr1 = new int [] {1,2,3,4,5,6,7,8,9,0};
int [] arr2 = new int [] {1,2,5,3,4,6,7,1,1,0};
var query = arr1.Zip(arr2, (i, j) => i != j).Select((b, i) => b ? (int?)i : null).Where(iptr => iptr.HasValue).Select(iptr => (int)iptr);
Debug.WriteLine(JsonConvert.SerializeObject(query.ToList())); // outputs [2,3,4,7,8]
This doesn't require the sequences to be arrays.
Related
From
int BinaryTable = new int[] { 1101 };
To
int BinaryTable = new int[] { 1,1,0,1 };
Don't know how to change it right.
int[] BinaryTable = new int[] { 1101 };
List<int[]> allItems = new List<int[]>();
foreach (var item in BinaryTable)
{
var items = item.ToString().Select(y => int.Parse(y.ToString())).ToArray();
allItems.Add(items);
}
var final = allItems.SelectMany(x => x).ToArray();
You could do it this way:
var bits = BinaryTable.Select(b =>
b.ToString().
Select(r => r == '0' ? 0 : 1))
.SelectMany(x => x);
This works if you want to get from
[1101,11] → [1,1,0,1,1,1]
. It is not really clear what exact do you want. And this solution doesn't check that your input really contains only 1 and 0 digits, since it is integer it could theoretically contain every number.
Quick and dirty LINQ:
int value = 1101; // a bit strange representation
int[] BinaryTable = value
.ToString()
.Select(c => c - '0')
.ToArray();
Or since 13 == 1101 binary:
int value = 13; // just an integer
int[] BinaryTable = Convert.ToString(value, 2)
.Select(c => c - '0')
.ToArray();
In case you want convert one array into another array, use SelectMany instead of Select:
int[] source = new int[] {1101};
int[] BinaryTable = source
.SelectMany(value => value.ToString()
.Select(c => c - '0'))
.ToArray();
Or
int[] source = new int[] {13};
int[] BinaryTable = source
.SelectMany(value => Convert
.ToString(value, 2)
.Select(c => c - '0'))
.ToArray();
I have an array of strings:
string[] stringArray = {"aaa", "bbb", "ccc", "aaa", "ccc", "ddd"};
I would like to get all indexes of this array where a substring of these strings are inside another array:
string[] searchArray = {"a","b"};
The answer I would like to get is then:
index = {0,1,3};
A soultion for just one entry of the searchArray would be:
List<int> index = stringArray.Select((s, i) => new { i, s })
.Where(t => t.s.Contains(searchArray[1]))
.Select(t => t.i)
.ToList();
A solution for all entries would be:
List<int> index = new List<int>();
foreach (string str in searchArray)
index.AddRange(stringArray.Select((s, i) => new { i, s })
.Where(t => t.s.Contains(str))
.Select(t => t.i)
.ToList());
index.Sort();
But out of curiosity, are there any solutions by just using one command in LINQ?
Yup, you just need Any to see if "any" of the target strings are contained in the array element:
List<int> index = stringArray
.Select((Value, Index) => new { Value, Index })
.Where(pair => searchArray.Any(target => pair.Value.Contains(target)))
.Select(pair => pair.Index)
.ToList();
I want to select array values from specific indexes
Now I have this.
var xs = new[] { 11,12,13,14,15 };
var ind = new[] { 3,2,1,0 };
var results = xs.Where((x, idx) => ind.Contains(idx)).ToArray();
The result is {11,12,13,14}
However, I want my result to be ordered by index array which should be {14,13,12,11}
Thank you very much
var results = ind.Select(i => xs[i]).ToArray();
var array = xs.Zip(ind, (x, i) => new Tuple<int, int>(x, i))
.OrderBy(t => t.Item2)
.Select(t => t.Item1)
.ToArray();
If you have two arrays string[] a and int[] b how can you get a Dictionary<string,int> from it most efficiently and with least code possible? Assume that they contain the same number of elements.
For example, is this the best way?
Dictionary<string,int> vals = new Dictionary<string,int>();
for(int i = 0; i < size; i++)
{
vals.Add(a[i],b[i]);
}
If your goal is to match at positions within the sequences, you can use Enumerable.Zip.
int[] myInts = { 1, 2 };
string[] myStrings = { "foo", "bar"};
var dictionary = myStrings.Zip(myInts, (s, i) => new { s, i })
.ToDictionary(item => item.s, item => item.i);
And since you are working with arrays, writing it "longhand" really isn't all that long. However, you want to validate beforehand the arrays truly are equal in length.
var dictionary = new Dictionary<string, int>();
for (int index = 0; index < myInts.Length; index++)
{
dictionary.Add(myStrings[index], myInts[index]);
}
Usually, Linq can result in more expressive, easier to understand code. In this case, it's arguable the opposite is true.
If this is .Net 4, then you can do the following:
var result = a.Zip(b, (first, second) => new {first, second})
.ToDictionary(val => val.first, val => val.second);
Without Zip, you can also do this:
var result = Enumerable.Range(0, a.Length).ToDictionary(i => a[i], i => b[i]);
Using ToDictionary:
int idx = 0;
var dict = b.ToDictionary(d => a[idx++]);
var result = a.ToDictionary(x => x, x => b[a.IndexOf(x)]);
I have an array of integers in string form:
var arr = new string[] { "1", "2", "3", "4" };
I need to an array of 'real' integers to push it further:
void Foo(int[] arr) { .. }
I tried to cast int and it of course failed:
Foo(arr.Cast<int>.ToArray());
I can do next:
var list = new List<int>(arr.Length);
arr.ForEach(i => list.Add(Int32.Parse(i))); // maybe Convert.ToInt32() is better?
Foo(list.ToArray());
or
var list = new List<int>(arr.Length);
arr.ForEach(i =>
{
int j;
if (Int32.TryParse(i, out j)) // TryParse is faster, yeah
{
list.Add(j);
}
}
Foo(list.ToArray());
but both looks ugly.
Is there any other ways to complete the task?
Given an array you can use the Array.ConvertAll method:
int[] myInts = Array.ConvertAll(arr, s => int.Parse(s));
Thanks to Marc Gravell for pointing out that the lambda can be omitted, yielding a shorter version shown below:
int[] myInts = Array.ConvertAll(arr, int.Parse);
A LINQ solution is similar, except you would need the extra ToArray call to get an array:
int[] myInts = arr.Select(int.Parse).ToArray();
EDIT: to convert to array
int[] asIntegers = arr.Select(s => int.Parse(s)).ToArray();
This should do the trick:
var asIntegers = arr.Select(s => int.Parse(s));
To avoid exceptions with .Parse, here are some .TryParse alternatives.
To use only the elements that can be parsed:
string[] arr = { null, " ", " 1 ", " 002 ", "3.0" };
int i = 0;
var a = (from s in arr where int.TryParse(s, out i) select i).ToArray(); // a = { 1, 2 }
or
var a = arr.SelectMany(s => int.TryParse(s, out i) ? new[] { i } : new int[0]).ToArray();
Alternatives using 0 for the elements that can't be parsed:
int i;
var a = Array.ConvertAll(arr, s => int.TryParse(s, out i) ? i : 0); //a = { 0, 0, 1, 2, 0 }
or
var a = arr.Select((s, i) => int.TryParse(s, out i) ? i : 0).ToArray();
C# 7.0:
var a = Array.ConvertAll(arr, s => int.TryParse(s, out var i) ? i : 0);
you can simply cast a string array to int array by:
var converted = arr.Select(int.Parse)
var asIntegers = arr.Select(s => int.Parse(s)).ToArray();
Have to make sure you are not getting an IEnumerable<int> as a return
var list = arr.Select(i => Int32.Parse(i));