Now I'm new for c# development.
I have 100 data from Array and also have 100 variables.
How can I match 100 data with 100 variables?
for example
for(int count = 0 ; count < array.lenght ; count++)
{
Var+count = array[count];
}
Something like this.
or you guy have another solution please help me. I don't want to do like
set Var1 to Var100 by hand.
More Information
Actually I need to add the arrays values to text object in CrystalReport
For example if I want to add the value
TextObject txtLot1 = (TextObject)report.ReportDefinition.Sections["Section4"].ReportObjects["txtLot1"];
txtLot1.Text = Arrays[i]
something like this. so , I try to use dictionary but I don't think it will work.
Here is an example of doing what you are asking for on the fly with a System.Collections.Generic.Dictionary, all keys in a dictionary must be unique, but since you are appending 1 to each key in your loop this will suffice:
Dictionary<string, int> myKeyValues = new Dictionary<string, int>();
for(int count = 0 ; count < array.length; count++)
{
//Check to make sure our dictionary does not have key and if it doesn't add key
if(!myKeyValues.ContainsKey("someKeyName" + count.ToString())
{
myKeyValues.Add("someKeyName" + count.ToString(), count);
}
else
{
//If we already have this key, overwrite, shouldn't happen as you are appending a new int value to key each iteration
myKeyValues["someKeyName" + count.ToString()] = count;
}
}
Related
I have a text file with most words in the English dictionary. I've created a hashset that contains each word so that I can compare a word to it and see if it is a real word. I now need to determine the number of times a certain string occurs in it.
For example, let's say a hashset contains the words: {"hello", "hi", "houses", "holder"}. If I want to check the number of occurrences of the string "ho", it should return the integer 2. Also, I want to do this instantly (in O(1) time).
I've tried making the hashset a string and checking that way with regex.matches, but it's simply way too long.
Thanks!
As you only mentioned the query time to be O(1) and not the creation of data structure we can do some bad things to achieve that.
We create a Dictionary<string> for a string and the number of occurrences of that string
We iterate through every string in HashSet we add every possible substring to Dictionary<string, int>. If substring does not exist we do .Add(s, 1) else we increment the string occurrances.
After that, you should be able to search in the Dictionary<string, int> in O(1).
Something like this:
var dict = new Dictionary<string, int>();
var hash = new HashSet<string> { "hello", "hi", "houses", "holder" };
foreach(var item in hash)
{
for(int i = 0; i < item.Length - 1; i++)
for(int j = i + 1; j < item.Length; j++)
{
var s = item.Substring(i, j - i);
if(!dict.ContainsKey(s))
{
dict.Add(s, 0);
}
dict[s]++;
}
}
And you got O(m*n^2) for data structure but querying is O(1).
If you do data structure calculation once in a lifetime this should do a good job. Creation of data structure will take time but it should be expected in some scenarios and you need some memory to store those strings.
To query for ho you use:
public int Query(string x) => dict.ContainsKey(x) ? dict[x] : 0;
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.
First of all,sorry for my bad english , i'm still learning.Now let's go back to my problem:
-I have a RichTextBox,where i introduce values like:
4112
3125
780
5680 etc.
-every value has a new line.What i mean is , after i introduce a value,i press ENTER.
All i want is,to save this values in an array,but as integer elements,not characters.How can I do that?
I tried with SplitChar method,but i don't understand this method,because i'm beginner in C#.
My try:
public void ViewMyTextBoxContents(){
//Create a string array and store the contents of the Lines property.
string[] tempArray = RichTextBox1.Lines;
// Loop through the array and send the contents of the array to debug window.
for(int counter=0; counter < tempArray.Length;counter++)
{
System.Diagnostics.Debug.WriteLine(tempArray[counter]);
} }
But still,not working ..Thanks for help!!!Have a nice day!
int[] arr = richTextBox1.Lines.Select(x => Int32.Parse(x)).ToArray();
Basically, you're missing the Int32.Parse(tempArray[counter]) part. This parses the string to an int.
Adapting your code to do the same:
string[] tempArray = richTextBox1.Lines;
int[] resultArr = new int[tempArray.Length];
for (int counter = 0; counter < tempArray.Length; counter++)
{
resultArr[counter] = Int32.Parse(tempArray[counter]);
}
Sorry for the newbie question. Could someone help me out? Simple array here. What's the best/easiest method to check all the user input is unique and not duplicated? Thanks
private void btnNext_Click(object sender, EventArgs e)
{
string[] Numbers = new string[5];
Numbers[0] = txtNumber1.Text;
Numbers[1] = txtNumber2.Text;
Numbers[2] = txtNumber3.Text;
Numbers[3] = txtNumber4.Text;
Numbers[4] = txtNumber5.Text;
foreach (string Result in Numbers)
{
lbNumbers.Items.Add(Result);
}
txtNumber1.Clear();
txtNumber2.Clear();
txtNumber3.Clear();
txtNumber4.Clear();
txtNumber5.Clear();
}
}
}
I should have added I need to check to happen before the numbers are output. Thanks
One simple approach is via LINQ:
bool allUnique = Numbers.Distinct().Count() == Numbers.Length;
Another approach is using a HashSet<string>:
var set = new HashSet<string>(Numbers);
if (set.Count == Numbers.Count)
{
// all unique
}
or with Enumerable.All:
var set = new HashSet<string>();
// HashSet.Add returns a bool if the item was added because it was unique
bool allUnique = Numbers.All(text=> set.Add(text));
Enunmerable.All is more efficient when the sequence is very large since it does not create the set completely but one after each other and will return false as soon as it detects a duplicate.
Here's a demo of this effect: http://ideone.com/G48CYv
HashSet constructor memory consumption: 50 MB, duration: 00:00:00.2962615
Enumerable.All memory consumption: 0 MB, duration: 00:00:00.0004254
msdn
The HashSet<T> class provides high-performance set operations.
A set is a collection that contains no duplicate elements, and whose
elements are in no particular order.
The easiest way, in my opinion, would be to insert all values inside a set and then check if its size is equal to the array's size. A set can't contain duplicate values, so if any value is duplicate, it won't be inserted into the set.
This is also OK in complexity if you don't have millions of values, because insertion in a set is done in O(logn) time, so total check time will be O(nlogn).
If you want something optimal in complexity, you can do this in O(n) time by going through the array, and putting each value found into a hash map while incrementing its value: if value doesn't exist in set, you add it with count = 1. If it does exist, you increment its count.
Then, you go through the hash map and check that all values have a count of one.
If you are just trying to make sure that your listbox doesn't have dups then use this:
if(!lbNumbers.Items.Contains(Result))
lbNumbers.Items.Add(Result);
What about this:
public bool arrayContainsDuplicates(string[] array) {
for (int i = 0; i < array.Length - 2; i++) {
for (int j = i + 1; j < array.Length - 1; j++) {
if (array[i] == array[j]) return true;
}
}
return false;
}
I'm trying to solve a simple algorithm a specific way where it takes the current row and adds it to the top most row. I know there are plenty of ways to solve this but currently I have a text file that gets read line by line. Each line is converted to an sbyte (there's a certain reason why I am using sbyte but it's irrelevant to my post and I won't mention it here) and added to a list. From there, the line is reversed and added to another list. Here's the code I have for that first part:
List<List<sbyte>> largeNumbers = new List<List<sbyte>>();
List<string> total = new List<string>();
string bigIntFile = #"C:\Users\Justin\Documents\BigNumbers.txt";
string result;
StreamReader streamReader = new StreamReader(bigIntFile);
while ((result = streamReader.ReadLine()) != null)
{
List<sbyte> largeNumber = new List<sbyte>();
for (int i = 0; i < result.Length; i++)
{
sbyte singleConvertedDigit = Convert.ToSByte(result.Substring(i, 1));
largeNumber.Add(singleConvertedDigit);
}
largeNumber.Reverse();
largeNumbers.Add(largeNumber);
}
From there, I want to use an empty list that stores strings which I will be using later for adding my numbers. However, I want to be able to add numbers to this new list named "total". The numbers I'll be adding to it are not all the same length and because so, I need to check if an index exists at a certain location, if it does I'll be adding the value I'm looking at to the number that resides in that index, if not, I need to create that index and set it's value to 0. In trying to do so, I keep getting an IndexOutOfRange exception (obviously because that index doesn't exist). :
foreach (var largeNumber in largeNumbers)
{
int totalIndex = 0;
foreach (var digit in largeNumber)
{
if (total.Count == 0)
{
total[totalIndex] = digit.ToString(); //Index out of Range exception occurs here
}
else
{
total[totalIndex] = (Convert.ToSByte(total[totalIndex]) + digit).ToString();
}
totalIndex ++;
}
}
I'm just at a loss. Any Ideas on how to check if that index exists; if it does not create it and set it's underlying value equal to 0? This is just a fun exercise for me but I am hitting a brick wall with this lovely index portion. I've tried to use SingleOrDefault as well as ElementAtOrDefault but they don't seem to be working so hot for me. Thanks in advance!
Depending on if your result is have small number of missing elements (i.e. have more than 50% elements missing) consider simply adding 0 to the list till you reach neccessary index. You may use list of nullable items (i.e. List<int?>) instead of regular values (List<int>) if you care if item is missing or not.
Something like (non-compiled...) sample:
// List<long> list; int index; long value
if (index >= list.Count)
{
list.AddRange(Enumerable.Repeat(0, index-list.Count+1);
}
list[index] = value;
If you have significant number of missing elements use Dictionary (or SortedDictionary) with (index, value) pairs.
Dictionary<int, long> items;
if (items.ContainsKey(index))
{
items[key] = value;
}
else
{
items.Add(index, value);
}