In my code i have an arraylist called array.
I have filled it with numbers from 1 to 13
for(int i =1; i< 14; i++)
{
array.items.Add(i)
}
Later in my code I also remove some of the elements at random.
Example array.remove(3);
Now I wanna search, how many values of the elements
in the arraylist is over specific number.
So, how many elements in the arraylist is over for example 5.
Anyone who knows how to do this?
Thanks!
Use this lambda expression:
int count = array.Cast<int>().Where(e=> e > 5).Count();
or even simpler:
int count = array.Cast<int>().Count(e=> e > 5);
You must be from Java right? I believe that you should use a List<T> in c#.
int count = array.Cast<int>().Count(x => x > 5);
OR change your arrayList to be an enumerable to allow.
int count = array.Count(x => x > 5);
array.Cast<int>().Where(item => item > 5).Count();
Related
Say I have the following List<List<string>>:
List<List<string>> input=new List<List<string>>();
for (int i = 0; i < 6; i++)
{
input.Add(new List<string>());
}
input[0]=new List<string>{"David","3","Ceviche"};
input[1]=new List<string>{"Corina","10","Beef Burrito"};
input[2]=new List<string>{"David","3","Fried Chicken"};
input[3]=new List<string>{"Carla","5","Water"};
input[4]=new List<string>{"Carla","5","Ceviche"};
input[5]=new List<string>{"Rous","3","Ceviche"};
How would I find the total count of distinct strings at input[i][1]? So in this case the count is 3 because you have "3","5","10"
What I have gives me 4
int count=input.SelectMany(x => x[1]).Distinct().Count();
Skip 1, Take 1.
int count=input.SelectMany(x => x.Skip(1).Take(1)).Distinct().Count();
SelectMany wants an IEnumerable, which is what Take returns. Note that this is uhm, more forgiving, than using an index, i.e. if the list doesn’t have the correct number of elements it doesn’t throw an exception. As long as that isn’t a problem for you (either not encountered or what you want, that should work just fine.
If I have a list of 100 integers, how would I assign the values at index 20 to 50 to a different set of values in a list of length 31 without the use of loops? Coming from python this is very easy to do without looping but am unsure if it is possible to do in c#.
Using LINQ, which is "without using loops in my code", you could:
hundredInts.Take(19).Concat(thirtyoneInts).Concat(hundredInts.Skip(50));
(and if you want it back as a list or array etc, the relevant ToXXX call on the end of it)
Or perhaps:
hundredInts.Select((n, i) => (i < 20 || i > 50) ? n : thirtyOneInts[i-20])
Or built in stuff:
hundredInts.RemoveRange(20, 31).InsertRange(20, thirtyOneInts);
There's no trivial way to do so with Lists. However, this is easily done with arrays using Array.Copy:
var destIndex = 20;
Array.Copy(sourceArray, 0, destArray, destIndex, sourceArray.Length)
Well, if you can use loops under the hood, you can create an extension method, like
public static class MyExtensions{
public static void SetRange<T>(this List<T> source, IEnumerable<T> newValues, int startIndex){
var newValuesList = newValues.ToArray();
int numberOfElements = Math.Min(source.Count - startIndex, newValues.Count());
for(int i = 0; i < numberOfElements; i++){
source[i + startIndex] = newValuesList[i];
}
}
}
And use like the following:
var list = Enumerable.Range(0, 100).ToList();
var list2 = Enumerable.Range(1000, 31).ToList();
list.SetRange(list2, 20);
This will replace the values in list, starting at index 20, to the values of list2. You can also modify the extension method to add another parameter to estipulate the number of elements that you will take from list2, like the following:
public static void SetRange<T>(this List<T> source, IEnumerable<T> newValues, int startIndex, int numberOfElements){
var newValuesList = newValues.ToArray();
numberOfElements = Math.Min(numberOfElements, source.Count - startIndex);
numberOfElements = Math.Min(numberOfElements, newValues.Count());
for(int i = 0; i < numberOfElements; i++){
source[i + startIndex] = newValuesList[i];
}
}
You should probably also add a validation if startIndex and numberOfElements are greater than or equal to 0.
I am attempting to code a one dimensional array to display code allowing me to display multiples of seven, I'm not sure how to go through with this, thank you.
I hope I understood your question. You can use generate multiples of 7 using Linq as follows.
var result = Enumerable.Range(1, 100).Select(x => x * 7).ToArray();
Enumerable.Range allows you to generate a sequence of values in specified range (First parameter is the first number in sequence, the second parameter is number of items), while the Select statement (x=>x*7, multiply each value in generated sequence with 7) ensures you get the multiples of 7.
Complete Code:
var result = Enumerable.Range(1, 100).Select(x => x * 7).ToArray();
foreach (var item in result)
{
Console.WriteLine(item);
}
Console.ReadLine();
Due to the vagueness of the question, my answer may not be applicable, but I will attempt to answer based on my assumption of what you are asking.
If you have an array of int and you want to multiply the values of the individual array objects, you would do something like this:
int[] myArray= { 3,5,8};
for (int i = 0; i < myArray.Length; i++)
{
Console.WriteLine(myArray[i]*7);
}
//outputs 21,35,56
If you want to multiply based on the index of the array object, you would do it like this:
int[] myArray= { 3,5,8};
for (int i = 0; i < myArray.Length; i++)
{
Console.WriteLine(i*7);
}
//outputs 0,7,14
//or if you need to start with an index of 1 instead of 0
int[] myArray= { 3,5,8};
for (int i = 0; i < myArray.Length; i++)
{
Console.WriteLine((i+1)*7);
}
//outputs 7,14,21
Anu Viswan also has a good answer, but depending on what it is you are trying to do, it may be better to rely on loops. Hope my answer helps.
I have classic find duplicate algorithm like this:
int n = int.Parse(Console.ReadLine());
Console.WriteLine();
List<int> tempArr = new List<int>();
List<int> array = new List<int>();
for (int i = 0; i < n; i++)
{
Console.Write("input number {0}: ", i + 1);
tempArr.Add(int.Parse(Console.ReadLine()));
}
tempArr.Sort();
for (int i = 0; i < n; i++)
{
for (int j = i+1; j < n; j++)
{
if (tempArr[i] == tempArr[j])
{
array.Add(tempArr[i]);
}
}
}
Everything work's okay, but if i have just two duplicate numbers like (1,2,2,3,4,5) how can i add them both to List<int> **array** with one clean shot at the loop ?
Instead of lists you could use some kind of data structure that have a better search capability (hash tables or binary trees, for example). Even if you have just one duplicate, the problem is that you need to check if you have already added the element in the list, so the key operation in your algorithm is the search. The faster you perform the search, the faster the algorithm will be. Using binary search, which is the fastest way to search, you get O(nlogn) (you perform n searches of O(logn)).
An even better way to do this is to have some kind of array that has the same size as your input range and "tick" each value that you already have. This search runs in constant time, but gets inefficient if you have a large range of input.
You can use distinct:
array = tempArr.Distinct().ToList();
Distinct isn't in linear time, if that's what you're looking for ("one clean shot"). If you know more about the input you might be able to find a way to do this in linear time. For example, if you know if the integers you take are in a certain range.
To extract all the duplicates you can use Linq:
List<int> tempList = new List<int>() { 1, 2, 2, 3, 4, 5 };
// array == [2, 2]
List<int> array = tempList
.GroupBy(x => x)
.Where(x => x.Count() > 1)
.SelectMany(x => Enumerable.Repeat(x.Key, x.Count()))
.ToList();
any one to help me solving this problem of mine?
I want to find biggest value inside a list inserted by keyboard something like this:
here it can be done by array:
int[] values = new int[10];
for (int i = 0; i < values.Length; i++)
{
values[i] = (int) (textbox.Text);
}
//to campare them
int bigValue=0;
for(int j=0;j<values.Lenght;j++)
{
if(bigValue<values[j])
{
bigValue==values[j];
}
}
////////////////////////////////
but in my code I have to use List I have filled the list but now I don't know the way to compare its values with each other to find the lowest and biggest one:
List<int> values= new List<int>();
values.Add((int)(textbox.Text));
Theres already built in functions for it, Max and Min:
int maxValue = values.Max();
int minValue = values.Min();
Your original function would work as well, substituting Count for Length, as indexing works with lists as well.
Use LINQ Min & Max functions:-
int LowestNumber = values.Min();
int HighestNumber = values.Max();
If you say you also need to use the list later in your program I guess you could find useful just to have it sorted.
values.Sort((value1, value2) => value1.CompareTo(value2));
With this option, minValue would be values[0] although the recomended way to find it is using the built in function as they have already mentioned.
You could just say something like this, which will work for any IEnumerable<int>, whether it's an int[], a List<int> or something else:
int? max = null ;
foreach( int value in someList )
{
max = (max??value) > value : (max??value) ;
}
At the end of this, If the list was empty, max will be null; otherwise max will have the highest value in the list.