Here is my code:
int Temp = 200;
List<int> PrimeBuilders = new List<int>();
PrimeBuilders.Add(200);
PrimeBuilders.Add(300);
PrimeBuilders.Add(400);
PrimeBuilders.Add(500);
PrimeBuilders.Add(200);
PrimeBuilders.Add(600);
PrimeBuilders.Add(400);
foreach(int A in PrimeBuilders)
{
}
How can I go through the list and output the index that does not contain the number assigned to Temp?
If you need indexed you probably should go with for instead of foreach:
for(int i = 0; i < PrimeBuilders.Count; i++)
{
if(PrimeBuilders[i] != Temp)
Console.WriteLine(i.ToString());
}
Bonus: LINQ one-liner:
Console.WriteLine(String.Join(Environment.NewLine, PrimeBuilders.Select((x, i) => new { x, i }).Where(x => x.x != Temp).Select(x => x.i)));
What you need is:
int Temp = 200;
var PrimeBuilders = new List<int> {200, 300, 400, 500, 200, 600, 400};
for (int i = 0; i < PrimeBuilders.Count; i++)
{
Console.WriteLine("Current index: " + i);
if (PrimeBuilders[i] != Temp)
{
Console.WriteLine("Match found at index: " + i);
}
}
Firstly, you can initialize your list with 1 line.
Secondly, if you need an index, then foreach will not give you that. You need a for loop, as shown above.
Related
int iterationMax = 1;
double actualMax = 0;
int A = 3;
List<double> tmp = new List<double> { 400, 0, -300, 400, 600 ,300, 400,
1200, 900, 400, 1200, 1500};
List<double> listMax = new List<double>();
for (int i = 0; i < tmp.Count; i++)
{
if (iterationMax < A) // A == 3
{
if (tmp[i] > actualMax)
{
actualMax = tmp[i];
}
iterationMax++;
}
else
{
listMax.Add(actualMax);
actualMax = 0;
iterationMax = 1;
}
}
Console.WriteLine("\nMaxs: ");
foreach (double max in listMax)
{
Console.Write(max + ", ");
}
List tmp holds = { 400,0,-300|400,600,300|400,1200,900|400,1200,1500},
Produce 400, 600, 1200, 1200,
Should be 400, 600, 1200, 1500. I don't know how to enter else statement to add 1500 to list.
I just want to get max from every 3 elements.
When one needs to perform manipulations on collection it is many times nicer to use Linq.
Use GroupBy in the index/3 and as it is an int each 3 following items will have a different key. Then for each group select the maximum value:
var items = new int[] { 400, 0, -300, 400, 600, 300, 400, 1200, 900 };
var results = items.Select((item, index) => new { item, index })
.GroupBy(item => item.index / 3)
.Select(group => group.Max(item => item.item));
//400, 600, 1200
A quick fix for your code would be:
var A = 3;
int iterationMax = 0;
double actualMax = 0;
List<double> tmp = new List<double> {400,0,-300,400,600,300,400,1200,900,400,1200,1500};
List<double> listMax = new List<double>();
for (int i = 0; i < tmp.Count; i++)
{
if (iterationMax < A) // A == 3
{
if (tmp[i] > actualMax)
{
actualMax = tmp[i];
}
iterationMax++;
}
if (iterationMax == A)
{
listMax.Add(actualMax);
actualMax = 0;
iterationMax = 0;
}
}
Console.WriteLine("\nMaxs: ");
foreach (double max in listMax)
{
Console.Write(max + ", ");
}
As others have said, start iterationMax from 0 and turn that else into an if (iterationMax == A).
Setting iterationMax to 0 in initialization and under else should solve your issue.
Currently your if structure will only check the first two out of three elements. Since 1500 is element #3, it will not be checked.
The problem is, when iterationMax reaches 3, you don't do anything with the value in temp, that loop is lost.
for (int i = 0; i < tmp.Count; i++)
{
if (tmp[i] > actualMax)
{
actualMax = tmp[i];
}
iterationMax++;
if (iterationMax > A)
{
listMax.Add(actualMax);
actualMax = 0;
iterationMax = 1;
}
}
I am trying to find the index of elements of my array using,
int[] arr = { 10, 20, 10 };
for ( int i; i,arr.length; i++)
{
int Tempval = arr[i];
index = Array.IndexOf(arr, Tempval);
console.writeline(index);
}
But its returning the same index for 10 i.e. 0 everytime.
How can I control it..??
Please help.
Regards
Do it like this:
int[] arr = { 10, 20, 10 };
for ( int i=0; i<arr.length; i++)
{
int Tempval = arr[i];
index = Array.IndexOf(arr, Tempval);
console.writeline(index);
}
Using LINQ you can do:
int[] arr = { 10, 20, 10 };
var result =
arr.Select((r, index) => new { Value = r, Index = index })
.GroupBy(item => item.Value)
.Where(grp => grp.Count() > 1)
.Select(r => new { Indexes = r.Select(t => t.Index).ToArray() })
.FirstOrDefault();
For output:
foreach (var value in result.Indexes)
Console.WriteLine(value);
Output would be:
0
2
You are already using loop and i is your index, why find index again?
int[] arr = { 10, 20, 10 };
for ( int i=0; i<arr.length; i++)
{
int Tempval = arr[i];
index = Array.IndexOf(arr, Tempval);
console.writeline(i);
}
If you want all the indexes,
public IEnumerable<int> FindIndexes(int[] array, int value)
{
for (int i = 0; i < array.Length; i++)
{
int Tempval = array[i];
if (Tempval == value)
{
yield return i;
}
}
}
and call FindIndexes(arr, 10);
I have a generic list of lists, trying to determine if there are already five equal numbers in each list.
If not find equals in lists, then add list into lists
this code work but I like learn more about linq.
how can do this using LINQ.
thank you
private void button2_Click(object sender, EventArgs e)
{
int n1 = (int)numericUpDown1.Value;
int n2 = (int)numericUpDown2.Value;
int n3 = (int)numericUpDown3.Value;
int n4 = (int)numericUpDown4.Value;
int n5 = (int)numericUpDown5.Value;
int n6 = (int)numericUpDown6.Value;
int n7 = (int)numericUpDown7.Value;
int n8 = (int)numericUpDown8.Value;
int n9 = (int)numericUpDown9.Value;
int n10 = (int)numericUpDown10.Value;
int n11 = (int)numericUpDown11.Value;
int n12 = (int)numericUpDown12.Value;
list = new List<int>();
list.Add(n1);
list.Add(n2);
list.Add(n3);
list.Add(n4);
list.Add(n5);
list.Add(n6);
list.Add(n7);
list.Add(n8);
list.Add(n9);
list.Add(n10);
list.Add(n11);
list.Add(n12);
if (data.Count == 0)
data.Add(list);
else
{
int l = data.Count;
bool eq =false;
for (int i = 0; i < l; i++)
{
int count = 0;
foreach (int n in list)
{
if (data[i].IndexOf(n) != -1)
++count;
if (count == 5)
{
eq = true;
break;
}
}
if (eq == true)
break;
}
if (eq == false)
data.Add(list);
else
{
// do nothing
}
}
}
you could use Intersect and Count extension methods.
something like
var exist = false;
foreach (var existingList in data) {
if (existingList.Intersect(list).Count() >=5) {
exist = true;
break;
}
if (!exist) data.Add(list);
But depending on the size of your lists, this will be far less performant, as the "check for intersects >= 5" will intersect all data of the lists.
trying to determine if there are already five equal numbers in each list. If not, then add them into lists
You can combine Enumerable.Count and loops, for example:
int n1 = (int)numericUpDown1.Value;
foreach(List<int> list in data)
{
int count = list.Count(i => i == n1);
while(count++ < 5)
list.Add(n1);
}
[EDIT] - please see the [UPDATE] below
I believe that your current code should look like:
...
int count = 0;
for (int i = 0; i < l; i++)
{
//int count = 0;
foreach (int n in list)
{
...
Anyway, to answer your question (if I understood correctly what you want to achieve) you may use this:
class Program
{
static List<List<int>> data;
static List<int> list;
static void Main(string[] args)
{
data = new List<List<int>>();
for (int i = 0; i < 6; i++)
{
list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(1);
var result = data
.Union(new[]{list})
.SelectMany(j => j)
.GroupBy(j => j)
.Select(j => new { j.Key, j })
.Where(j => j.j.Count() > 4);
if (result.Count() == 0)
data.Add(list);
}
}
}
[UPDATE]
Ok, I think I understood what you want to achieve: if there are no other lists in data that have at least 5 elements in common with the list, the list should be added to the data, which is a List<List<int>>.
var result = data.Any(i => i.Intersect(list).Count() > 4);
if(!result)
data.Add(list);
Given your code you've posted, I think the solution is:
List<int> list = new List<int>();
List<List<int>> data = new List<List<int>>();
if (data.All(l => l.Intersect(list).Count() < 5))
data.Add(list);
I have the following:
var list = new List<double[]>();
list.Add(new double[] { 300, 12, 22 });
list.Add(new double[] { 310, 13, 23 });
list.Add(new double[] { 320, 14, 24 });
list.Add(new double[] { 330, 15, 25 });
I would like to get from this a multidimensional array containing the first 2 columns:
double[,] a = { {300,12}, {310,13}, {320,14}, {330,15}}
Can I do this using linq? And how?
Try the following
var a = list.Select(x => new [] { x[0], x[1] }).ToArray();
EDIT
Didn't realize at first the intent was to get a non-jagged 2d array out of the source. Unfortunately there isn't really a way to do that with the standard LINQ methods. They deal mostly in terms of IEnumerable<T> and T[]. However there is nothing stopping you from creating a new method which does this
public static T[,] ToMultidimensionArray<T>(this List<T[]> list, int columns)
{
var array = new T[list.Count, columns];
for (int i = 0; i < list.Count; i++)
{
var source = list[i];
for (int j = 0; j < columns; j++)
{
array[i, j] = source[j];
}
}
return array;
}
Now you can convert the original list with a simple query
var a = list.ToMultidimensionArray(2);
LINQ and multi-dimensional arrays do not mix well. Array.Copy is not applicable here as well.
Use a traditional for loop:
double[,] result = new double[list.Count, 2];
for (int i = 0; i < list.Count; i++)
{
result[i, 0] = list[i][0];
result[i, 1] = list[i][1];
}
public static T[,] GetColumns<T>(IList<IEnumerable<T>> source, int numColumns)
{
T[,] output = new T[source.Count, numColumns];
for (int i = 0; i < source.Count; i++)
{
int j = 0;
foreach (T item in source[j].Take(numColumns))
{
output[i, j] = item;
j++;
}
}
return output;
}
Note that in this case if any of the lists contain an array that doesn't have enough values to fill all of the columns you want then they'll be left with default values, it won't throw an exception. You'll need to check for it and throw one yourself if you want that to happen.
var array = list.Select(item => item.Take(2).ToArray()).ToArray();
foreach (var item in array)
{
Console.WriteLine("{0}, {1}", item[0], item[1]);
}
How to get the most common value in an Int array using C#
eg: Array has the following values: 1, 1, 1, 2
Ans should be 1
var query = (from item in array
group item by item into g
orderby g.Count() descending
select new { Item = g.Key, Count = g.Count() }).First();
For just the value and not the count, you can do
var query = (from item in array
group item by item into g
orderby g.Count() descending
select g.Key).First();
Lambda version on the second:
var query = array.GroupBy(item => item).OrderByDescending(g => g.Count()).Select(g => g.Key).First();
Some old fashioned efficient looping:
var cnt = new Dictionary<int, int>();
foreach (int value in theArray) {
if (cnt.ContainsKey(value)) {
cnt[value]++;
} else {
cnt.Add(value, 1);
}
}
int mostCommonValue = 0;
int highestCount = 0;
foreach (KeyValuePair<int, int> pair in cnt) {
if (pair.Value > highestCount) {
mostCommonValue = pair.Key;
highestCount = pair.Value;
}
}
Now mostCommonValue contains the most common value, and highestCount contains how many times it occured.
I know this post is old, but someone asked me the inverse of this question today.
LINQ Grouping
sourceArray.GroupBy(value => value).OrderByDescending(group => group.Count()).First().First();
Temp Collection, similar to Guffa's:
var counts = new Dictionary<int, int>();
foreach (var i in sourceArray)
{
if (!counts.ContainsKey(i)) { counts.Add(i, 0); }
counts[i]++;
}
return counts.OrderByDescending(kv => kv.Value).First().Key;
public static int get_occure(int[] a)
{
int[] arr = a;
int c = 1, maxcount = 1, maxvalue = 0;
int result = 0;
for (int i = 0; i < arr.Length; i++)
{
maxvalue = arr[i];
for (int j = 0; j <arr.Length; j++)
{
if (maxvalue == arr[j] && j != i)
{
c++;
if (c > maxcount)
{
maxcount = c;
result = arr[i];
}
}
else
{
c=1;
}
}
}
return result;
}
Maybe O(n log n), but fast:
sort the array a[n]
// assuming n > 0
int iBest = -1; // index of first number in most popular subset
int nBest = -1; // popularity of most popular number
// for each subset of numbers
for(int i = 0; i < n; ){
int ii = i; // ii = index of first number in subset
int nn = 0; // nn = count of numbers in subset
// for each number in subset, count it
for (; i < n && a[i]==a[ii]; i++, nn++ ){}
// if the subset has more numbers than the best so far
// remember it as the new best
if (nBest < nn){nBest = nn; iBest = ii;}
}
// print the most popular value and how popular it is
print a[iBest], nBest
Yet another solution with linq:
static int[] GetMostCommonIntegers(int[] nums)
{
return nums
.ToLookup(n => n)
.ToLookup(l => l.Count(), l => l.Key)
.OrderBy(l => l.Key)
.Last()
.ToArray();
}
This solution can handle case when several numbers have the same number of occurences:
[1,4,5,7,1] => [1]
[1,1,2,2,3,4,5] => [1,2]
[6,6,6,2,2,1] => [6]