Need to add each number 0-x to end of line? - c#

I'm making an app and I'm almost done. I just need to know how I can streamread a txt list and foreach line, add numbers 0-x (x will be the number the user puts in the textbox) and add it to a list. So basically, it would be like this
You import a list with 'dog' on one line, 'cat' on another, and 'fish' on the third. You type '5' into the textbox. the app puts all this into a list:
dog1
dog2
dog3
dog4
dog5
cat1
cat2
cat3
cat4
cat5
fish1
fish2
fish3
fish4
fish5
thanks!

The code below should work for you. I assume you can acquire the count value on your own.
var animals = File.ReadAllLines("yourFile.txt"); //new[] {"dog", "cat", "fish"};
var count = 5;
var merged =
from a in animals
from n in Enumerable.Range(1, count)
select a + n;
foreach (var m in merged)
Console.WriteLine(m); //act on each however you want

You can read a text file with File.ReadAllLines. This gives you an array you can iterate over with foreach.
In this foreach loop you can perform another loop from 1 to the number the user entered. int.Parse comes in handy for converting the string the user entered into a number C# can do something with. For the actual iteration you can use a for loop.
You can then add each item to a list.

There is a good example for reading each line in a filestream here: http://msdn.microsoft.com/en-us/library/e4y2dch9.aspx

private List<string> GetThings(string fileName, int count)
{
string[] lines = File.ReadAllLines(fileName);
List<string> result = new List<string>();
foreach (string item in lines)
{
for (int i = 1; i <= count; i++)
result.Add(item + i.ToString());
}
return result;
}

string[] inputList = File.ReadAllLines("yourFile.txt");
List<String> listOfThings = new List<String>();
foreach (string i in inputList)
{
for (int k = 0; k < 5; k++)
{
listOfThings.Add(i + " " + k.ToString());
}
}
then after that, you can print out the list like this:
foreach (string outp in listOfThings)
{
Console.WriteLine(outp);
}
output:
some value 0
some value 1
some value 2
some value 3
some value 4
some other value 0
some other value 1
some other value 2
some other value 3
some other value 4

Related

Sorting a list in c# (custom defined sorting rules)

I have a list of string called choosedGroupList consisting of 5 items. Each item represents a group,
For example: L1andL4 means that L1 will be grouped with L4.
Another example: L1,L4andL5,L6 means that the group L1,L4 will be grouped with the group L5,L6
I am trying to sort this list to be like this:
L1andL4
L5andL6
L1,L4andL5,L6
L2andL1,L4,L5,L6
L3andL2,L1,L4,L5,L6
So I wrote this code to perform this task,
//sorting choosedGroupList
for (int k = 0; k < choosedGroupList.Count; k++)
{
for (int j = k + 1; j < choosedGroupList.Count; j++)
{
string[] parts = choosedGroupList[j].Split(new string[] { "and" }, StringSplitOptions.None);
if (parts[0] == choosedGroupList[k].Replace("and", ",") || parts[1] == choosedGroupList[k].Replace("and", ","))
{
string[] parts2 = choosedGroupList[k + 1].Split(new string[] { "and" }, StringSplitOptions.None);
//if (parts[0] != parts2[0] || parts[1] != parts2[1])
//{
String Temp = choosedGroupList[k + 1];
choosedGroupList[k + 1] = choosedGroupList[j];
choosedGroupList[j] = Temp;
//}
}
}
}
I have no exceptions in the code but, I do not get the desired results.
After executing the code this is the result:
L1andL4
L1,L4andL5,L6
L2andL1,L4,L5,L6
L5andL6
L3andL2,L1,L4,L5,L6
Assumption 1: you wish to sort first by number of 'L's then by the numbers following the 'L's.
The major issue in the code given is that you never check the length of the arrays, so L1,L4 will always sort before L5 because L1 sorts before L5.
If you split on 'and' separately from ',' and sort on length of the array split from ',' first before sorting on the contents of that array, then it should match your proposed sort order.
How about using a Dictionary?
public static Dictionary<string, int> YourDictionary()
{
Dictionary<string, int> returnDict = new Dictionary<string, int>();
returnDict.Add("L1andL4", 1);
returnDict.Add("L5andL6", 2);
returnDict.Add("L1,L4andL5,L6", 3);
returnDict.Add("L2andL1,L4,L5,L6", 4);
returnDict.Add("L3andL2,L1,L4,L5,L6", 5);
return returnDict;
}
Then iterate over the Dictionary:
var theDictionary = clsProdDesign.YourDictionary();
var items = from pair in theDictionary orderby pair.Value ascending select pair;
foreach (KeyValuePair<string, int> pair in items)
{
//do whatever
}

Add item in list in specific position

I'm trying to find if i can add an item in list in specific position.
Example
string[] tokens= new string[10];
tokens[5]="TestString";
when i'm trying this to list
List<string> mitems = new List<string>();
mitems.Insert(5, "TestString");
I'm getting error list inside a list index out of range.
Is there any relative to this for a list?
Use the Insert(index, item); method.
Have a look at MSDN Insert for more information.
But you will get an error when you're trying to insert an item at an index which is not existing.
You could init your list with 10 empty values like you did with your array but if you use Insert a new entry is created and not an old replaced like with a dictionary. That would mean you would have 11 entries after the first use of Insert
This example code
var items = new List<string>();
items.AddRange(Enumerable.Repeat(string.Empty, 10));
Console.WriteLine(items.Count);
items.Insert(5, "TestString");
Console.WriteLine(items.Count);
gives this output (for better understanding):
10
11
private static void Myfunc()
{
List<string> l = new List<string>();
string opt = "y";
while (opt == "y")
{
Console.WriteLine("Do you want to add in a specific position? (y/n)");
string pos = Console.ReadLine();
if (pos == "y")
{
Console.WriteLine("Which index you want to add?");
int index = Convert.ToInt16(Console.ReadLine());
Console.WriteLine("Add items in {0}", index);
l.Insert(index, Console.ReadLine());
}
else
{
Console.WriteLine("Enter to add in a list");
l.Add(Console.ReadLine());
Console.WriteLine("Do you wish to continue? (y/n)");
opt = Console.ReadLine();
}
Console.WriteLine("Do you want to print the list? (y/n)");
string print = Console.ReadLine();
if (print == "y")
{
foreach (var item in l)
{
Console.WriteLine(item);
}
}
}
I wrote this function for you.
Add this function to a console app for better understanding how list works for insert and append
EDIT 1:
I just saw your edit, another way of initializing a list with default values and then insert something in a certain position would be by initializing the list like this :-
List<string> l = Enumerable.Repeat("something blank", 10).ToList();
And then add to an index of your choice
Following adds default values of string at every index from 0-9
string[] tokens= new string[10];
But list is created on heap nothing instantiated. No default assigned values.
List<string> mitems = new List<string>();
If you try following it will fail as there are no values at 0-5
mitems.Insert(5, "TestString");
If you do following it will work
mitems.Insert(0, "TestString");
You can use List<T>.Insert(int, T) method to do that, example:
var tokens = new List<string>();
for (int i = 0; i < 10; i++)
tokens.Add(string.Empty);
tokens.Insert(5, "TestString");
See MSDN
Edit:
If you were just trying to replace the item in index of 5, than the [] will also do the trick as following example:
var tokens = new List<string>(10);
for (int i = 0; i < 10; i++)
tokens.Add(string.Empty);
tokens[5] = "TestString";

Summation/Add two values inside foreach loop

I want to add Array items inside forach loop.
My RegionalEarn array comes like this,
[0]Region1=25
[1]Region2=50
I need final RModel.TAX Should be 75(25+50) But in my case it comes like 2550
My Code
string[] RegionalEarn = tickets["EARN"].ToString().Split(',');
foreach (var item in RegionalEarn)
{
RModel.TAX = RModel.TAX + item.Split('=')[1];
}
You're adding strings, not numbers. You can use the TryParse method on for example the Int32 type to try convert a string to an int. The other numbers types have a similar TryParse method. If your number comes with extra signs, dots or commas, apply the the overload that accepts a FormatProvider matching the Numberstyle or a Culture the number is from.
string[] RegionalEarn = tickets["EARN"].ToString().Split(',');
var sum =0;
foreach (var item in RegionalEarn)
{
var num = 0;
if (Int32.TryParse(item.Split('=')[1], out num))
{
sum = sum + num;
}
else
{
// log error, item.Split('=')[1] is not an int
}
}
RModel.TAX = sum.ToString();
actually you done like concatenation.it comes only string values. so try convert to int or double .
string[] RegionalEarn = tickets["EARN"].ToString().Split(',');
foreach (var item in RegionalEarn)
{
RModel.TAX = Convert.ToInt32(RModel.TAX) + Convert.ToInt32( item.Split('=')[1]);
}
This is a simple way to do it.
string[] RegionalEarn = tickets["EARN"].ToString().Split(',');
foreach (var item in RegionalEarn)
{
RModel.TAX = (int.Parse(RModel.TAX) * item.Split('=').Sum (p => int.Parse(p))).ToString();
}
The above will take RModel.TAX multiply it with the sum of the values in the item array using Sum() method. This should give you the correct result.

how to count an element in each index of Arraylist in c#

First, I have a string that contain all of characters and then I add it into Arraylist of list1 but I separate it with *. so now I have 5 elements of arraylist.
String fString = "DAVCFW_ACK*DAVCFW_20_30_90*DAVCFW_15.5_20.1_35.0*DAVCFW_40_230_110*DAVCFW_END";
ArrayList list1 = new ArrayList();
string[] words = fString.Split('*');
foreach (string s in words)
{
list1.Add(s);
}
Second, I delete first 6 charecters of each elements and keep it into Arraylist of list2.
ArrayList list2 = new ArrayList();
String s1 = list1.ToString();
foreach(string s in list1){
for (int i = 0; i < s.Length; i++ ){
if(i>6){
list2[i-7] = list1[i];
}
}
}
Third, I delete all _ characters of each elemeant and keep it into Arraylist of list3. Now I get only number not characters.
ArrayList list3 = new ArrayList();
String[] word_s1 = s1.Split('_');
foreach(string s in word_s1){
list3.Add(s);
}
And then I would like to keep the value of list3 like matrix but still is an Arraylist. I need to know number of element in each index of list3 to define row and colomn. For column I think I can use list3.count; but for row I don't know how. After I know row. I have to put 0 to element in each index that have number of row less than row.
Pleas Help me. Thanks you.
Did you ever run this code? First of all it doesn't work, because in second listing you are trying to get list1[7], where last index is 5. Second, in the same listing you are accesing element in subloop, not characters. Third, why did you do that String s1 = list1.ToString()? s1 is equal to string "System.Collections.ArrayList".
Back to your question. If you want to get length of every row, just use string.Length property. Here is working code:
String fString = "DAVCFW_ACK*DAVCFW_20_30_90*DAVCFW_15.5_20.1_35.0*DAVCFW_40_230_110*DAVCFW_END";
ArrayList list1 = new ArrayList();
string[] words = fString.Split('*');
foreach (string s in words)
{
list1.Add(s);
}
ArrayList list2 = new ArrayList();
foreach(string s in list1)
{
list2.Add(s.Substring(6));
}
ArrayList list3 = new ArrayList();
foreach (string s in list2)
{
list3.Add(s.Replace("_", string.Empty));
}
foreach (string s in list3)
{
Console.WriteLine(s);
}
Console.WriteLine("Number of rows: {0}", list3.Count);
for (int i = 0; i < list3.Count; i++)
{
Console.WriteLine("Number of characters in {0} row: {1}",i, (list3[i] as string).Length);
}
The question is not very clear about what you want. If you are after a matrix of item position as column, and values as rows, you can try something like this.
String fString = "DAVCFW_ACK*DAVCFW_20_30_90*DAVCFW_15.5_20.1_35.0*DAVCFW_40_230_110*DAVCFW_END";
Dictionary<int, ArrayList> matrix = new Dictionary<int,ArrayList>();
string[] words = fString.Split('*');
for (int i = 0; i < words.Length - 2 ; i++) // exclude the first and the last words because they do not have number
{
string[] numbers = words[i+1].Substring(6).Split('_');
ArrayList list = new ArrayList();
for (int j = 1; j < numbers.Length; j++) // exlcude the first number as it is empty string
{
list.Add(numbers[j]);
}
matrix[i] = list;
}

Can't create nested list because list.Clear doesn't seem to work as I want

I try to load txt file that consists of 200 rows each of different length into nested list so that every sublist inside main list will be equal to row, so there will be 200 sublists.
class MainClass
{
public static void Main (string[] args)
{
List<List<int>> arrayList = new List<List<int>>();
List<int> tmp = new List <int> ();
string[] file = File.ReadAllLines(#"C:\file.txt");
foreach (string line in file) {
string[] linef = line.Split (new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
tmp.Clear ();
for (int n = 0; n < linef.Length; n++) {
tmp.Add (int.Parse (linef [n]));
}
arrayList.Add (tmp);
}
But arrayList seams to contain only last row - whenever i try to get some number, for a example arrayList[78][5], it gives me 5th number from 200th row no matter what the first index is - 78 or other. I think there is issue with tmp.Clear but i cant figure out how to make it work.
Because you are re-adding the same List<int> tmp many times to arrayList, so that at the end
bool areSame = object.ReferenceEquals(arrayList[0], arrayList[1]); // true
You have one List<int> with n references to it (one for each "row" of arrayList)
Change it to:
foreach (string line in file) {
List<int> tmp = new List <int> ();
// No Clear necessary
tmp.Clear() makes your list empty, that is all. The main list contains only 200 references to your tmp list.
You have to call
tmp = new List<int>();
instead of
tmp.Clear();

Categories