Summation/Add two values inside foreach loop - c#

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.

Related

C# looping through a list to find character counts

I'm trying to loop through a string to find the character, ASCII value, and the number of times the character occurs. So far, I have found each unique character and ASCII value using foreach statements, and finding if the value was already in the list, then don't add it, otherwise add it. However I'm struggling with the count portion. I was thinking the logic would be "if I am already in the list, don't count me again, however, increment my frequency"
I've tried a few different things, such as trying to find the index of the character it found and adding to that specific index, but i'm lost.
string String = "hello my name is lauren";
char[] String1 = String.ToCharArray();
// int [] frequency = new int[String1.Length]; //array of frequency counter
int length = 0;
List<char> letters = new List<char>();
List<int> ascii = new List<int>();
List<int> frequency = new List<int>();
foreach (int ASCII in String1)
{
bool exists = ascii.Contains(ASCII);
if (exists)
{
//add to frequency at same index
//ascii.Insert(1, ascii);
//get { ASCII[index]; }
}
else
{
ascii.Add(ASCII);
//add to frequency at new index
}
}
foreach (char letter in String1)
{
bool exists = letters.Contains(letter);
if (exists)
{
//add to frequency at same index
}
else
{
letters.Add(letter);
//add to frequency at new index
}
}
length = letters.Count;
for (int j = 0; j<length; ++j)
{
Console.WriteLine($"{letters[j].ToString(),3} {"(" + ascii[j] + ")"}\t");
}
Console.ReadLine();
}
}
}
I'm not sure if I understand your question but that what you are looking for may be Dictionary<T,T> instead of List<T>. Here are examples of solutions to problems i think you trying to solve.
Counting frequency of characters appearance
Dictionary<int, int> frequency = new Dictionary<int, int>();
foreach (int j in String)
{
if (frequency.ContainsKey(j))
{
frequency[j] += 1;
}
else
{
frequency.Add(j, 1);
}
}
Method to link characters to their ASCII
Dictionary<char, int> ASCIIofCharacters = new Dictionary<char, int>();
foreach (char i in String)
{
if (ASCIIofCharacters.ContainsKey(i))
{
}
else
{
ASCIIofCharacters.Add(i, (int)i);
}
}
A simple LINQ approach is to do this:
string String = "hello my name is lauren";
var results =
String
.GroupBy(x => x)
.Select(x => new { character = x.Key, ascii = (int)x.Key, frequency = x.Count() })
.ToArray();
That gives me:
If I understood your question, you want to map each char in the provided string to the count of times it appears in the string, right?
If that is the case, there are tons of ways to do that, and you also need to choose in which data structure you want to store the result.
Assuming you want to use linq and store the result in a Dictionary<char, int>, you could do something like this:
static IDictionary<char, int> getAsciiAndFrequencies(string str) {
return (
from c in str
group c by Convert.ToChar(c)
).ToDictionary(c => c.Key, c => c.Count());
}
And use if like this:
var f = getAsciiAndFrequencies("hello my name is lauren");
// result: { h: 1, e: 3, l: 3, o: 1, ... }
You are creating a histogram. But you should not use List.Contains as it gets ineffective as the list grows. You have to go through the list one item after another. Better use Dictionary which is based on hashing and you go directly to the item. The code may look like this
string str = "hello my name is lauren";
var dict = new Dictionary<char, int>();
foreach (char c in str)
{
dict.TryGetValue(c, out int count);
dict[c] = ++count;
}
foreach (var pair in dict.OrderBy(r => r.Key))
{
Console.WriteLine(pair.Value + "x " + pair.Key + " (" + (int)pair.Key + ")");
}
which gives
4x (32)
2x a (97)
3x e (101)
1x h (104)
1x i (105)
3x l (108)
2x m (109)
2x n (110)
1x o (111)
1x r (114)
1x s (115)
1x u (117)
1x y (121)

How can I split a string to store contents in two different arrays in c#?

The string I want to split is an array of strings.
the array contains strings like:
G1,Active
G2,Inactive
G3,Inactive
.
.
G24,Active
Now I want to store the G's in an array, and Active or Inactive in a different array. So far I have tried this which has successfully store all the G's part but I have lost the other part. I used Split fucntion but did not work so I have tried this.
int i = 0;
for(i = 0; i <= grids.Length; i++)
{
string temp = grids[i];
temp = temp.Replace(",", " ");
if (temp.Contains(' '))
{
int index = temp.IndexOf(' ');
grids[i] = temp.Substring(0, index);
}
//System.Console.WriteLine(temp);
}
Please help me how to achieve this goal. I am new to C#.
If I understand the problem correctly - we have an array of strings Eg:
arrayOfStrings[24] =
{
"G1,Active",
"G2,Inactive",
"G3,Active",
...
"G24,Active"
}
Now we want to split each item and store the g part in one array and the status into another.
Working with arrays the solution is to - traverse the arrayOfStrings.
Per each item in the arrayOfStrings we split it by ',' separator.
The Split operation will return another array of two elements the g part and the status - which will be stored respectively into distinct arrays (gArray and statusArray) for later retrieval. Those arrays will have a 1-to-1 relation.
Here is my implementation:
static string[] LoadArray()
{
return new string[]
{
"G1,Active",
"G2,Inactive",
"G3,Active",
"G4,Active",
"G5,Active",
"G6,Inactive",
"G7,Active",
"G8,Active",
"G9,Active",
"G10,Active",
"G11,Inactive",
"G12,Active",
"G13,Active",
"G14,Inactive",
"G15,Active",
"G16,Inactive",
"G17,Active",
"G18,Active",
"G19,Inactive",
"G20,Active",
"G21,Inactive",
"G22,Active",
"G23,Inactive",
"G24,Active"
};
}
static void Main(string[] args)
{
string[] myarrayOfStrings = LoadArray();
string[] gArray = new string[24];
string[] statusArray = new string[24];
int index = 0;
foreach (var item in myarrayOfStrings)
{
var arraySplit = item.Split(',');
gArray[index] = arraySplit[0];
statusArray[index] = arraySplit[1];
index++;
}
for (int i = 0; i < gArray.Length; i++)
{
Console.WriteLine("{0} has status : {1}", gArray[i] , statusArray[i]);
}
Console.ReadLine();
}
seems like you have a list of Gxx,Active my recomendation is first of all you split the string based on the space, which will give you the array previoulsy mentioned doing the next:
string text = "G1,Active G2,Inactive G3,Inactive G24,Active";
string[] splitedGItems = text.Split(" ");
So, now you have an array, and I strongly recommend you to use an object/Tuple/Dictionary depends of what suits you more in the entire scenario. for now i will use Dictionary as it seems to be key-value
Dictionary<string, string> GxListActiveInactive = new Dictionary<string, string>();
foreach(var singleGItems in splitedGItems)
{
string[] definition = singleGItems.Split(",");
GxListActiveInactive.Add(definition[0], definition[1]);
}
What im achiving in this code is create a collection which is key-value, now you have to search the G24 manually doing the next
string G24Value = GxListActiveInactive.FirstOrDefault(a => a.Key == "G24").Value;
just do it :
var splitedArray = YourStringArray.ToDictionary(x=>x.Split(',')[0],x=>x.Split(',')[1]);
var gArray = splitedArray.Keys;
var activeInactiveArray = splitedArray.Values;
I hope it will be useful
You can divide the string using Split; the first part should be the G's, while the second part will be "Active" or "Inactive".
int i;
string[] temp, activity = new string[grids.Length];
for(i = 0; i <= grids.Length; i++)
{
temp = grids[i].Split(',');
grids[i] = temp[0];
activity[i] = temp[1];
}

Convert Array List to Comma Separated String in C#

I'm using String.Join to attempt to turn an array list into a string that is comma separated, such as
xxx#xxx.com,yyy#xxx.com,zzz#xxx.com,www#xxx.com
I can't seem to get the syntax working.
Here's what I'm trying:
for (i = 0; i < xxx; i++)
{
MailingList = arrayList[i].ToString();
MailingList = string.Join(", ", MailingList.ToString());
Response.Write(MailingList.ToString());
}
Can you help me?
Thank you in advance-
Guessing from the name of your variable (arrayList), you've got List<string[]> or an equivalent type there.
The issue here is that you're calling ToString() on the array.
Try this instead:
for (i = 0; i < xxx; i++)
{
var array = arrayList[i];
MailingList = string.Join(", ", array);
Response.Write(MailingList);
}
EDIT: If arrayList is simply an ArrayList containing strings, you can just do
Response.Write(string.Join(", ", arrayList.OfType<string>()));
Personally I would avoid using nongeneric collections (such as ArrayList) if possible and use strongly-typed collections from System.Collections.Generic such as List<string>. For example, if you have a piece of code that depends on that all contents of the ArrayList are strings, it will suffer catastrophically if you accidentally add an item that's not a string.
EDIT 2: If your ArrayList actually contains System.Web.UI.WebControls.ListItems like you mentioned in your comment: arrayList.AddRange(ListBox.Items);, then you'll need to use this instead:
Response.Write(string.Join(", ", arrayList.OfType<ListItem>()));
The second parameter for String.Join needs to be an IEnumerable. Replace MailingList.ToString() with arrayList and it should work.
Initialization:
string result = string.Empty;
For value types:
if (arrayList != null) {
foreach(var entry in arrayList){
result += entry + ',';
}
}
For reference types:
if (arrayList != null) {
foreach(var entry in arrayList){
if(entry != null)
result += entry + ',';
}
}
And cleanup:
if(result == string.Empty)
result = null;
else
result = result.Substring(0, result.Length - 1);
most of the answers are already there, still posting a complete - working snippet
string[] emailListOne = { "xxx#xxx.com", "yyy#xxx.com", "zzz#xxx.com", "www#xxx.com" };
string[] emailListTwo = { "xxx#xxx1.com", "yyy#xxx1.com", "zzz#xxx1.com", "www#xxx1.com" };
string[] emailListThree = { "xxx#xxx2.com", "yyy#xxx2.com", "zzz#xxx2.com", "www#xxx.com" };
string[] emailListFour = { "xxx#xxx3.com", "yyy#xxx3.com", "zzz#xxx3.com", "www#xxx3.com" };
List<string[]> emailArrayList = new List<string[]>();
emailArrayList.Add(emailListOne);
emailArrayList.Add(emailListTwo);
emailArrayList.Add(emailListThree);
emailArrayList.Add(emailListFour);
StringBuilder csvList = new StringBuilder();
int i = 0;
foreach (var list in emailArrayList)
{
csvList.Append(string.Join(",", list));
if(i < emailArrayList.Count - 1)
csvList.Append(",");
i++;
}
Response.Write(csvList.ToString());

Add two values from two different Lists

Again another one of those moments when my brain has completely failed me.
I am trying to add(Addition) two values(decimals) from two separate Lists. In all honesty i think I'm running into value type issues but any clarification welcome.
public List<decimal> getTotalSellingPrice(int costSheetID)
{
List<decimal> totalSellingPrice = new List<decimal>();
decimal bothMarkupAndToms = 0;
foreach (var i in getMarkupPrice(costSheetID))
{
foreach (var m in getToms(costSheetID))
{
bothMarkupAndToms = i + m;
}
totalSellingPrice.Add(Math.Round(bothMarkupAndToms));
}
return totalSellingPrice;
}
As you can see for each item in each collection i want to add to another value within the nested collection.
So on each pass it should "i + m" then add to the final list ready for the UI.
Any help would be extremely appreciated!
This will give you the sum of each value from getTotalSellingPrice() with it's corresponding value from getToms(). If both the lists have 4 values each this will give you 4 values in the resulting list. What you were doing was more like permutation. This is proper addition of two lists.
public List<decimal> getTotalSellingPrice(int costSheetID)
{
List<decimal> totalSellingPrice = new List<decimal>();
List<object> toms = getToms(costSheetID);
int j = 0,
tomsCount = toms.Count;
foreach (var i in getMarkupPrice(costSheetID))
{
if(j >= tomsCount )
break;
totalSellingPrice.Add(Math.Round(i + Convert.ToDecimal(toms[j])));
j++;
}
return totalSellingPrice;
}
For each value in getMarkupPrice(), the above code is adding the corresponding value from toms (based on the index j it uses to track the current value in toms) and adding the result in the totalSellingPrice list. The additional if block inside the foreach checks if the toms is out of values. If yes, the break; statement just exits the execution of that foreach loop.
The problem is with your 2 foreach loops. You're creating i * m values with your code instead of matching i to m and then adding them. For each i you get 4 m so 4 * 4 will give you 16 values.
If you want to put an item (i+m) into the list, try the following:
public List<decimal> getTotalSellingPrice(int costSheetID)
{
List<decimal> totalSellingPrice = new List<decimal>();
foreach (var i in getMarkupPrice(costSheetID))
{
foreach (var m in getToms(costSheetID))
{
totalSellingPrice.Add(Math.Round(i + m));
}
}
return totalSellingPrice;
}
And if you want to out an item for each i (sum of all m for that i) try the following:
public List<decimal> getTotalSellingPrice(int costSheetID)
{
List<decimal> totalSellingPrice = new List<decimal>();
decimal bothMarkupAndToms = 0;
foreach (var i in getMarkupPrice(costSheetID))
{
bothMarkupAndToms = i;
foreach (var m in getToms(costSheetID))
{
bothMarkupAndToms += m;
}
totalSellingPrice.Add(Math.Round(bothMarkupAndToms));
}
return totalSellingPrice;
}
I hope that help
Edit:
I think you are try to add corresponding elements from those two lists, for example first element from markup prices with first element from toms and so on. Based on that scenario you want something like bellow:
public List<decimal> getTotalSellingPrice(int costSheetID)
{
List<decimal> totalSellingPrice = new List<decimal>();
decimal bothMarkupAndToms = 0;
List<decimal> markupPriceList = getMarkupPrice(costSheetID);
List<decimal> tomsList = getToms(costSheetID);
for(int i = 0 ; i < tomsList.size() ; i++)
{
totalSellingPrice.Add(Math.Round(markupPriceList[i] + tomsList[i]));
}
return totalSellingPrice;
}

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

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

Categories