c# indexer for list of list - c#

hi all
i want to make an indexer to list of list to get items like this myopj[i,j] .
my data structure is like this :
list<list<doubl>>
i try code like this but it not work
public double this[int r, int c]
{
set
{
if (this.list1.Count == 0 )
{
this.list1[r].Add(value);
}
else
this.list1[r][c]=value;
}
}
when i watch it the program don't enter the 'if' and it end the watch .
please is there anyone can help
and thank for all .

You should be checking the count, not the capacity. Capacity is the number of elements the list can have, the Count is the actual number of items in your list.
So, given a list that is not null, the capacity should NEVER be zero, but the count could be.

It seems rather strange that your value is either a list<T> or a T.
Without more information, I suggest you implement this using a single, long list of T.
You will then translate myList<T>[i,j] to the underlying list<T>[ i * numRows + j].
Sprinkle validations as required.
If you really, really must use lists of lists figure out if you want to end up with a rectangular matrix (i.e. the list at row i has the same number of elements as the list at row j), or a staggered array (where each list has an independent number of elements).
If you're in the first case, consider creating and filling the row lists automatically, with the appropriate number of elements( use default<T> to initialize them)
Update:
Then, if what you really need is a rectangular matrix then use a list.
It will have numRows * numColumns elements.
Imagine that, instead of putting one row under the other to make a matrix, you put the elements of a row one after the other.
So, if you have:
11 12 13
21 22 23
31 32 33
in a list form they will be
11 12 13 21 22 23 31 32 33
There is a simple conversion between the X and Y (or i and j) coordinates in the first form and the index in the list in the second form.

Why are you checking the capacity? It will likely never be zero. Did you mean to check the Count?

You want the length property, and not Capactiy.
Use:
if (this.list1.Count < r )
Your algorithm doesn't really make much sense, you might want to describe what you are trying to accomplish. It looks like you are trying to make it grow if its not large enough, but the logic in the two seperate paths(if else) doesn't align.

Related

Best way to search through a object list to evaluate a certain variable from that object?

I hope I am explaining this clearly. I'm trying to figure out a good (or the best) way to search through a list of objects to evaluate one particular variable before making a decision.
Imagine I have a List, the Person class contains three variables (Name, Age, Favorite color) and my list looks like below:
Bob, 69, Blue
Fred, 64, Green
Billy, 29, Yellow
Ted, 16, Orange
So my list contains 4 objects, and I would like to check the list to make sure that no one on the list is in the age range of 30 - 50. What is going to be the best way to do this?
my initial thought was to do a foreach loop, and for every iteration that a person's age is not in the 30 - 50 range I would increment a int variable. then at the end check to see if the int variable is equal to the count of the list. Sounds terrible thinking about it out loud, and if the list grew to 1000+ then I can imagine it wouldn't be the fastest way to look through the list and verify that no ones age falls within that range. Any help would be greatly appreciated, thanks!
You could do
people.Any(x => x.Age <= 50 && x.Age >= 30)
It'll return a bool of whether any age has a value of 30-50

C# - How to find a difference between lowest and highest numbers

I have a List that contains multiple numbers like this:
1.75
1.25
2.03
1.44
What I want to do, is to find a difference between lowest and highest number. In this case it would be 1.25 and 2.03, which would make 0.78.
How should I do it?
The steps are quite simple:
Find the largest number in the list
Find the smallest number in the list
The result you need = [Result of 1] - [Result of 2]
To implement this you can use LINQ:
// Intialize your list (or use the existing one)
var list = new List<decimal>{ 1.75m, 1.25m, 2.03m, 1.44m};
// The result is maximum of the list minus minimum of the list
var result = list.Max() - list.Min();
// Print or use the result
Console.WriteLine(result); // prints the result 0.78
first determine the maximum and the minimum number and then substract the min from the max.
There are a few different ways you can do it, but first a few questions:
Is the list sorted? If it is, then it's really simple.
If it's not sorted, then you may iterate through the list, an have two variables "min" and "max", and in the end just find the difference.
Are you given the list? If not and you are the one adding values to the list, then you can keep track of the added values, and assign them appropriately to your "min" and "max" variables.
You can use LINQ

Deduce a downward trend from a list of values

In of the functions in my program that is called every second I get a float value that represents some X strength.
These values keep on coming at intervals and I am looking to store a history of the last 30 values and check if there's a downward/decreasing trend in the values (there might be a 2 or 3 false positives as well, so those have to neglected). If there's a downward trend and (If the most recent value minus the first value in the history) passes a threshold of 50 (say), I want to call another function. How can such a thing be implemented in C# which has such a structure to store history of 30 values and then analyse/deduce the downward trend?
You have several choices. If you only need to call this once per second, you can use a Queue<float>, like this:
Queue<float> theQueue = new Queue<float>(30);
// once per second:
// if the queue is full, remove an item
if (theQueue.Count >= 30)
{
theQueue.Dequeue();
}
// add the new item to the queue
theQueue.Enqueue(newValue);
// now analyze the items in the queue to detect a downward trend
foreach (float f in theQueue)
{
// do your analysis
}
That's easy to implement and will be plenty fast enough to run once per second.
How you analyze the downward trend really depends on your definition.
It occurs to me that the Queue<float> enumerator might not be guaranteed to return things in the order that they were inserted. If it doesn't, then you'll have to implement your own circular buffer.
I don't know C# but I'd probably store the values as an List of some sort. Here's some pseudo code for the trend checking:
if last value - first value < threshold
return
counter = 0
for int i = 1; i < 30; i++
if val[i] > val[i-1]
counter++
if counter < false_positive_threshold
//do stuff
A Circular List is the best data structure to store last X values. There doesn't seem to be one in the standard library but there are several questions on SO how to build one.
You need to define "downward trend". It seems to me that according to your current definition ((If the most recent value minus the first value in the history) the sequence "100, 150, 155, 175, 180, 182" is a downward trend. With that definition you only need to the latest and first value in history from the circular list, simplifying it somewhat.
But you probably need a more elaborate algorithm to identify a downward trend.

How to get number of elements in an array, Extension Method Count() and Length gives the size of Array.

Hi I was trying to find the number of elements in an array
byte[] salt = new byte[32];
now I only have mentioned size 32 so the Length Property of Array and Enumerable's Count Method will give me 32.
Even if I will iterate on this Array salt using for or foreach or any other looping construct it will iterate 32 times and on each index the value is 0 (i.e default value of byte)
Now suppose I do:
for (int i = 0; i < 5 ; i++)
{
salt[i] = 4-i;
}
And I want to know how many elements are inserted sequentially in Array starting from index 0, Here you may say are you fool you iterating it 5 times and you know the number is 5 , but I am having heavy looping and other logic (appending prepending to another arrays of byte) in it. *My question Is there any other inbuilt function that could give me this number 5 ? * Even if I iterate and check for first default value and break the loop there and get the count but there might be the chance last value inserted is 0 like above salt[4] is 0 so that iterating will give me the count 4 which is incorrect . If I am not wrong I think when we declare Array with size like 32 above 32 consecutive memory bytes are reserved and you are free to insert at any index from 0-31 and its your responsibility to keep the track where and how and how many elements are assigned to Array .I hope you got my point And thanks in advance for help.
An array is an array, and in .NET is initialized when it is allocated. Once it's initialized, the question of whether a given value is uninitialized or simply 0 isn't something that's possible to check. A 0 is a 0.
However, you can bypass that in several ways. You can use a List<int>, like #SLaks suggested, to have a dynamically allocated list that's only initialized with the elements you want.
You can also use, instead of an array of int, and array of int?, so a null value isn't the same as a 0.
Short answer is you can't, the array contains 32 integers, .net framework doesn't care if some of them are 0, so you can create your own function that counts how many integers from an array are different than 0, or keep a "count" when you assign values for array elements or something like that.
Or you can use another container, example a list and dynamically add or remove integers from it.
Ok, when you define an array as int[] myArray = int[32]; you are saying, I HAVE 32 ints. Not, create me space for 32 ints that I will fill in later. That's why count is giving you 32.
If you want something which you can genuinly add to and resize, you need to use a List (or one of it's relatives.
If you want to have a "cap" for a list, I found this :Maximum capacity collection in c#

How to sort numbers

I need some help to be able to handle the following logic. The program gets many integers input like 10,16,3,17,21,29,6.
Logic to be done:
Scenario 1:
First select the biggest 4 numbers of input which is 16,17,21,29. Now assign the values to A,B,C and D:
A = smallest in the selected 4
B = biggest in the selected 4
C =
second smallest in the selected 4
D = third smallest in the selected
4
Result to be Displayed:
A = 16
B = 29
C = 17
D = 21
Scenario: 2
If the user gives 3 inputs like 3,6,10 assign only to A,B,C and should ignore D
Result to be Displayed:
A = 3
B = 10
C = 6
Assuming that you have your input values in an array, you can sort it using the static Array.Sort() method and then pick the top/bottom ones by indexing (eg. values[value.Length - 1] gets the highest value). Do make sure to do some bounds checking to avoid runtime exceptions, and to solve "scenario 2" of the assignment correctly.
If you want something more modern, you could also use some LINQ magic to get the top 4 items:
values = values.OrderByDescending(i => i).Take(4).ToArray();
The four highest values are now in highOnes for you to print in whatever order you please. Once again, make sure to do some bounds checking - there might be less than four numbers in the array.
I would take the input and store them into a List. I would then sort this list.
Once sorted you can then pull out the numbers as required.
Logic:
Sort in descending order
Select top 4 element
Assign value as per your requirement in A,B,C,D
Sounds like this could be an assignment so I'll give you these tips:
If you have all these numbers in an array, you can try partially sorting the array. Write a simple bubble sort, and have it sort the largest numbers to the front. But instead of sorting the whole array, make it stop after it brings the 4 largest elements to the front of the array.
That way, your first element will be your largest, and so forth. From there, you can do the rest of the things you need easily.
Hope that helped.

Categories