C# equivalent of php foreach loop on array [closed] - c#

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].

Related

how can i fix System.IndexOutOfRangeException: 'Index was outside the bounds of the array.' in my undo and redo? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 1 year ago.
Improve this question
I'm writing an undo and redo for my notepad. This is my undo and redo code and I have a System.IndexOutOfRangeException exception, how can I fix this? Is there another way to do this?
string[] temp = new string[100];
int index;
int currentpostion;
public Undo()
{
index = 0;
currentpostion = 0;
}
public void Set_Text(string s)
{
temp[index] = s;
currentpostion = index;
++index;
}
public string UndoCons()
{
if (currentpostion > 0)
{
return temp[--currentpostion];
}
return null;
}
public string RedoCosns()
{
if (currentpostion < index)
{
return temp[++currentpostion];
}
return null;
}
}
This error occurs when the array is full. What can I do? Can anyone improve this algorithm?
One simple solution would be to use a List instead of an array.
List<string> temp = new List<string>();
It will need some tweaks but it will not limit you to 100 actions.
In any other case, you should decide the strategy. Do you want to delete the initial items? Then remove your first X items and replace them with the latest ones.

How to loop through a multidimensional list [closed]

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 7 years ago.
Improve this question
Must be a simple question, and I'm again close to a nervous breakdown because I can't find it:
I have a multimensional List that I defined as an own class (Id, Title, Desc, Start, Length, URL) and that I filled in one function
hyperlist.Add(
new ListElement
{
Id = n,
Title = title,
Desc = desc,
Start = OffsetTotal,
Length = TagLength,
URL = LinkURL
});
I pass it to another function where I have to loop through it and compare each entry of the list to a parameter.
void BuildGList(List<ListElement> LinkList)
{
int startIndex = 5;
foreach (int Id in LinkList)
{
if(startIndex < Start)
{
....
}
}
}
I don't see how to address each single column and googling it I get the impression that nobody uses lists to do what I want here.
-update-
I am asked to clarify my question. Lucky enough it had been clear to the ones that answered it: I didn't know how to refer to a special parameter in a List. Now I know that you can do it with item.parameter.I'm really grateful for the help received in Stackoverflow but sometimes I get the impression that many of you experienced coders have little empathy and understanding for the problems a beginner faces and the effort it takes to google through a jungle of posts. Especially if you are a beginner and therefore sometimes miss the correct keywords. On this one I was busy for an hour and close to a breakdown as I knew I was catching really simple. If you know it then it's always easy. Cheers
You can use foreach like this:
foreach (ListElement item in LinkList)
{
if (item.Length < startIndex)
{
//Do something
}
}
You can filter the list using Linq e.g. to return an IEnumerable as the subset you could do:
private IEnumerable<ListElement> BuildGList(List<ListElement> linkList)
{
int startIndex = 5;
return linkList.Where(element => startIndex < element.Start);
}
You can use takewhile with a foreach if you want to use the list index:
foreach(var item in LinkList.TakeWhile((item, index) => index < startIndex))
{
//enter your code here
}
Also, if you want to compare with a element value inside the list, you can use where with the foreach:
foreach(var item in LinkList.Where(item => item.Start < startIndex))
{
//enter your code here
}

Is this emitted code useful? [closed]

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 7 years ago.
Improve this question
While looking through some dll's with ILSpy I came across the following code:
void RenderFiles(List<List<string>> pdfFiles)
{
int num;
for (int i = 0; i < pdfFiles.Count; i = num + 1)
{
// ....
num = i;
}
}
The introduction of the num variable seems strange to me. Why would the compiler introduce an extra local variable?
The original code is just a simple loop, although it uses a count variable and not a foreach enumerator:
void RenderFiles(List<List<string>> pdfFiles)
{
for (int i = 0; i < pdfFiles.Count; i++)
{
}
}

Getting the Values from Dictionary [closed]

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 8 years ago.
Improve this question
I am going Round-Robin Algorithm. I am doing in that everything must be created dynamically and Randomly. When I want to go second time to check if I have and value the is more than 0 in the checking point it says that "The given key was not present in the dictionary". How can I Fix this problem.
private int GetNextNodeToProcesssRandom()
{
int NextNodeIndex = -1;
if (NextNodeToProcess >= this.waytosave.Count)
{
NextNodeToProcess = 0;
}
for (int i = NextNodeToProcess; i < this.waytosave.Count; i++)
{
if (this.waytosave[i] > 0)//the problem appears here when the cod goes for the second time.
{
NextNodeIndex = i;
break;
}
}
NextNodeToProcess++;
return NextNodeIndex;
}
It is somehow unclear what is your exact goal. However if you want to loop through a Dict you can use:
foreach(KeyValuePair<TKey, TValue> entry in MyDict)
{
// do something with entry.Value or entry.Key
}
Now if you want to add a check in your program you can try:
if (MyDict.ContainsKey(this.waytosave[i]))
///continue execution...
A look here might help you

Need Logic to Add Counts [closed]

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();
}

Categories

Resources