Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Improve this question
i have a following data in 3 sets.
EUR5-002,EUR10-000,
EUR20-001,EUR50-001,
EUR100-001,EUR200-000,
EUR500-000
EUR5-000,EUR10-000,
EUR20-002,EUR50-001,
EUR100-001,EUR200-000,
EUR500-000
EUR5-001,EUR10-001,
EUR20-002,EUR50-001,
EUR100-002,EUR200-003,
EUR500-000
Here EUR - CurrencyID and 5,10,20,50,100,200,500 are currency values. And the values after "-" is no of notes of the corresponding denomination.(EUR5-002, means 2 notes of 5 EUROs)
In my code I have read each set as string and added to List.
I need a logic in C# using regex or someother to add each individual denomination count from all 3 sets of data.
From the above data, I have to get the output as below.
EUR5-003,EUR10-001,
EUR20-005,EUR50-003,
EUR100-004,EUR200-003,
EUR500-000
Code does not handles any errors which can be caused by wrong input format, you can maintain it for yourself.
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var data = new [] {
"EUR5-002,EUR10-000,EUR20-001,EUR50-001,EUR100-001,EUR200-000,EUR500-000",
"EUR5-000,EUR10-000,EUR20-002,EUR50-001,EUR100-001,EUR200-000,EUR500-000",
"EUR5-001,EUR10-001,EUR20-002,EUR50-001,EUR100-002,EUR200-003,EUR500-000"
};
var results = new Dictionary<string, int>();
foreach (var line in data)
{
var entries = line.Split(',');
foreach (var entry in entries)
{
var parts = entry.Split('-');
string key = parts[0];
if (!results.ContainsKey(key))
{
results[key] = 0;
}
results[key] += int.Parse(parts[1]);
}
}
foreach (var result in results)
{
Console.WriteLine(result.Key + "-" + result.Value.ToString("000"));
}
Console.ReadLine();
}
}
}
You can do it this way
//limit is the highest value of currency
int temp=0;
for(int x=1;x<=limit;x++,temp=0)
{
if((temp=parseDenomination(x,input))!=0)
output+=","+"EUR"+x+"-"+temp;
}
//output has your desired output
private static int parseDenomination(int no,String input)
{
return Regex.Matches(input,#"(?<=EUR"+no+#"-)\d+")
.Cast<Match>()
.Select(x=>int.Parse(x.Groups[0].Value))
.ToList()
.Sum();
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have following code in my project
var ReturnStr = Final_BOM.Tables[0].Rows[0]["NEW_BOM_IDS"].ToString();
the above line returns "12,13" but some times only "12"
var ReturnBOM = dsBOMDEfault.Tables[0].Rows[0]["Item_ID"].ToString();
the above line returns "14,15,13".
I want to check ReturnBOM values in ReturnStr
Can any one help how to check
You can use intersect:
Here a quick one-liner:
var results = ReturnStr.Split(',').Select(int.Parse)
.Intersect(ReturnBOM.Split(',').Select(int.Parse))
Demo:
using System;
using System.Linq;
public class Program
{
public static void Main()
{
var ReturnStr = "12,13";
var ReturnBOM = "14,15,13";
// Convert string to array with Split(',')
// if you dont want int just remove `.Select(int.Parse)`
var ReturnStrElements = ReturnStr.Split(',').Select(int.Parse);
var ReturnBOMElements = ReturnBOM.Split(',').Select(int.Parse);
// Keep only common elements
var results = ReturnStrElements.Intersect(ReturnBOMElements);
foreach(var item in results)
{
Console.WriteLine(item);
}
}
}
We use Split() to convert a string to an array where the delimiter is ','
[Optional] We use Select(int.Parse) to convert each element from string to int.
We use Intersect() to keep only common elements
Use LINQ.
using System.Linq;
The below code will give you an IEnumerable of String with the values you are looking for.
var inBoth = ReturnStr.Split(',').Intersect(ReturnBOM.Split(','))
You may then iterate through the values, cast them to Int32 or do whatever action you want.
If i understanded rights:
string[] returnBomVals = ReturnBom.Split(',');
string[] returnStrVals = ReturnStr.Split(',');
foreach (var vals in returnStrVals)
{
foreach (var strVals in returnBomVals)
{
if (ReturnStr.Equals(vals))
{
//Do Actions
}
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
This is what I have so far...
using System;
using System.Collections.Generic;
using System.IO;
class Solution
{
static void Main(String[] args)
{
string testCaseNumber = Console.ReadLine();
string string1 = Console.ReadLine();
string string2 = Console.ReadLine();
List<char> evenIndex1 = new List<char>();
List<char> oddIndex1 = new List<char>();
for (int i = 0; i <= 10000; i++)
{
if (i % 2 == 0)
{
if (i == string1.Length)
{
break;
}
else
{
char even = string1[i];
evenIndex1.Add(even);
}
}
else
{
if(i == string1.Length)
{
break;
}
else
{
char odd = string1[i];
oddIndex1.Add(odd);
}
}
}
Console.Write(evenIndex1);
}
}
I also did a ton and I'm still really stumped. I'm a beginner so there is a lot of things I still don't know.
How do I print to the console the even indexed numbers in C#?
There are so many ways in which you can do it. Here are a few of them:
replace this:
Console.Write(evenIndex1);
with this:
evenIndex1.ForEach(Console.WriteLine); //requires importing -> using System.Linq;
another way:
foreach(var item in evenIndex1) Console.Write(item + " ");
You could also concatenate all the items within the collection using String.Join then print it like this:
Console.Write(string.Join(",", evenIndex1));
further reading on how the methods used work:
String.Join Method
List.ForEach Method
Try this:
Console.WriteLine(string.Join(" ", oddIndex1.ToArray()));
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have the following for loop written in PHP:
$activesFilters = 0;
foreach ($_GET as $key => $value) {
if(!empty($value)) $activesFilters++;
}
if(isset($_GET['Filter'])) { $activesFilters = $activesFilters - 1; }
if(isset($_GET['CustomFilter'])) { $activesFilters = $activesFilters - 1; }
if(isset($_GET['showArchived'])) { $activesFilters = $activesFilters - 1; }
and I want to convert it over to ASP.NET C# Razor.
So far I have:
int activeFilter = 0;
#foreach(Request.QueryString as key in value) {
if(!empty(value)) activeFilters+1;
}
#if(Request.QueryString['Filter']) activeFilters = activeFilters - 1;
#if(Request.QueryString['CustomFilter']) activeFilters = activeFilters - 1;
#if(Request.QueryString['showArchived']) activeFilters = activeFilters - 1;
It's the foreach loop I'm confused about.
As I don't understand how to handle the key => value in C#
I've written the above based on: http://msdn.microsoft.com/en-us/library/ttw7t8t6(v=vs.90).aspx but it doesn't show any examples for handling the key + value part.
UPDATE:
Based on some help from below:
#int activeFilters = 0;
#foreach (string key in Request.QueryString)
{
string value = Request.QueryString[key];
if(String.IsNullOrEmpty(value)){
return activeFilters+1;
}
}
However it says activeFilters does not exist in the current context. How do I expose it to the foreach loop in C#? As this is fine in the PHP world.
foreach (string key in Request.QueryString)
{
string value = Request.QueryString[key];
// add your other code here
}
Now, you iterate over all keys in the query string, and then you get their values using Request.QueryString[key].
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I need a way to get the response from a user.
For example they type "hat" and it displays the price in the array table in a console writeline. It also needs to be done in a 2d array instead of dictionary
class Table
{
string[,] names = {
{"rice", "50"},
{"chip", "20"},
{"hat", "50"},
{"ball", "34"},
};
}
class Program
{
static void Main(string[] args)
{
string Res;
Console.WriteLine("What product would you like?");
Res = Console.ReadLine();
Console.ReadKey();
}
}
Use a Dictionary<string, string> rather that way you can look up the Value based on the Key
Dictionary<string, string> example = new Dictionary<string, string>();
example.Add("hat", "50");
//Add the rest in this manner
The you can do the lookup like this
if (example.ContainsKey(Res))
string price = example[Res];
Straightforward solution with 2-d array:
class Program
{
static void Main(string[] args)
{
var products = new[,] { {"rice", "50"}, {"chip", "20"}, {"hat", "50"}, {"ball", "34"} };
Console.WriteLine("What product would you like?");
var request = Console.ReadLine();
string value = null;
if (request != null)
{
for (int i = 0; i < products.GetUpperBound(0); i++)
{
if (products[i, 0] == request)
{
value = products[i, 1];
break;
}
}
}
if (!string.IsNullOrEmpty(value))
{
Console.WriteLine("You've selected: " + request + ". Value is: " + value);
}
else
{
Console.WriteLine("You've selected: " + request + ". No value found.");
}
Console.ReadKey();
}
}
you should be using a Dictionary instead of your jagged array. It is better and you get more flexibility.
var items = new Dictionary<string, string>(5);
items.Add("rice", "50");
items.Add("chip", "20");
// and so on
then you get the item by checking to see if the key exists first:
if (items.ContainsKey("rice"))
{
// it exists! read it:
Console.WriteLine(items["rice"]);
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
The question is on C#.
I have a string "value1=1234;value2=2345;value3=3456;value4= ..."
What is the best way to retrieve the values?
I thought about String.Split(";") but I don't know how to retrieve the values only. The result I get includes the prefix I don't want.
I only want the values of "1234", "2345", "3456"... nothing else, and them put them into a list of strings.
How do I solve this? Thanks.
If the format is always fixed, you can do it fairly easily via LINQ:
List<string> values = theString.Split(';').Select(s => s.Split('=')[1]).ToList();
Note that you may want to use RemoveEmptyEntries if your input string ends in a semi-colon:
List<string> values = theString
.Split(new[]{';'}, StringSplitOptions.RemoveEmptyEntries)
.Select(s => s.Split('=')[1]).ToList();
This would prevent an exception from occuring within the Select. If the input doesn't end in a semi-colon, however, this wouldn't be necessary.
var text = "value1=1234;value2=2345;value3=3456;value4= ...";
var pieces = text.Split('=');
var values = new Dictionary<string,string>();
for(int index = 0; index < pieces.Length; index += 2)
{
values.Add(pieces[index], pieces[index + 1]);
}
This will give you a dictionary of the pairs where the key is the left-hand side of the '=' and the value is the string representation of the value, which allows your to do:
var value1 = values["value1"];
var value2 = values["value2"];