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
}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
What i want to do is to use something like this Console.Writeline($"Name {Key} - Points: {Value}");
but i dont know how to make the data from the txt into Keys and Values.
I see, you want to fill a Dictionary<string, int> with the names and points of people, right?
If yes then I would suggest never use a dictionary Keys for names, because names are the data that can be duplicate which will eventually lead your software to throw exceptions regarding that.
Make a Generic List of custom class data. Something like this:
public class UserPoint
{
public string Name { get; set; }
public int Points { get; set; }
}
Then like below you can read your text file and load the data into the Generic List.
public static void Main(string[] args)
{
var lines = System.IO.File.ReadAllLines(#"myfile.txt"); // I assume each user info is separated by a newline.
var pointsList = new List<UserPoint>();
foreach(var line in lines)
{
var splittedLine = line.Split(';');
if(splittedLine.Length < 1) continue;
var userPoint = new UserPoint { Name = splittedLine[0].Trim() };
if(splittedLine.Length > 1 && int.TryParse(splittedLine[1].Trim(), out var points)) // updated the direct conversion to safe conversion with tryparse.
{
userPoint.Points = points; // To get rid of extra parsing you can also keep Points property as string.
}
pointsList.Add(userPoint);
}
}
PS: There are multiple other ways to read the text file but I used a simple way, You can also use FileStream and StreamReader classes if you like. Read more on reading text files on these MSDN Articles.
EDIT:
I notice you want to iterate and print through the list as well, you can do in the first loop or you can write a loop again. See:
foreach(var userPoint in pointsList)
{
Console.WriteLine($"Name: {userPoint.Name}, Points: {userPoint.Points}");
}
EDIT 2:
OP has asked to sort the list in descending order based on the points value. Here is a solution for that:
pointsList = pointsList.OrderByDescending(userPoint => userPoint.Points).ToList();
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I solved this codility test with the following code:
private static int lesson2_1(int[] A) {
if (!Isvalid(A))
{
return -1;
}
List<int> d = A.Distinct().ToList();
foreach (var item in d)
{
var q = from one in A where one == item select one;
if (q.Count() == 1)
{
return item;
}
}
return -1;
}
private static bool Isvalid(int[] a)
{
if (a.Length == 0)
{
return false;
}
return true;
}
These are the results:
I do not know how to approach this, since I have not learned yet about complexity. Can someone please guide me to the right approach to this issue?
Many thanks
My advice - don't reinvent the wheel. .Net has a lot built into it. Chances are unless you have specialist requirements Microsoft will be able to implement it better than you. The following gets a 100% score:
using System;
using System.Linq;
class Solution {
public int solution(int[] A) {
return A.GroupBy(a => a).First(a => a.Count() %2 == 1).Key;
}
}
There are a few issues with your solution.
1) You aren't following the test spec. It states
all but one of the values in A occur an even number of times.
That means that the number you are looking for could occur, 3,5,7,etc. times - you are just checking for 1.
2) The time complexity of your solution is poor. You are looping through every item and doing a search for each item within every loop. This isn't necessary if you think about it. You will have to go through every item in the list but if you process it as you go along you effectively only have to go through each item once and then the buckets of each item once.
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 2 years ago.
Improve this question
I've been looking up a lot of videos, tried using the bubble sort method, insert sort method, but nothing seems to work for this particular problem. I am supposed to add a string (movie name) to an array, but I must do it alphabetically. I can not sort the array after it's completed, it must be done while I add the new strings.
I've seen a lot posts with similar questions like this but all of them sort the array after its completed!
Here is a couple of methods that might help you.
private void PrintAlphabetically()
{
string[] movies = new string[5];
movies[0] = "b";
movies[1] = "x";
movies[2] = "m";
movies[3] = "a";
movies[4] = "t";
AddToStringArray(ref movies, "s");
Array.Sort(movies, (x, y) => String.Compare(x , y));
for (int i = 0; i < movies.Length; i++)
{
Console.WriteLine(movies[i]);
}
}
private void AddToStringArray(ref string[] array, string item)
{
List<string> list = array.OfType<string>().ToList();
list.Add(item);
array = list.ToArray();
}
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 6 years ago.
Improve this question
i want my if loop to do nothing when the conditions that i gave it are there
i'm new to C# and winform so i searched the internet but didnt find an answer that seems to work and right now i have no idea what to do.
,Mo
screenshot of the loop
If I understand your question correctly, you want to "cancel" all operations in the current method, right? You can use return; to do that:
if(value2 == null) return;
There is just one other thing wrong with your code: value2 will never be null.
decimal value2;
if(!decimal.TryParse(result[1], out value2)) return;
should work a lot better ;)
I can't see any loop in the code provided. You want to change Parse to TryParse and use return in order to return from the method (== do nothing):
public void button14_Click(Object sender, EventArgs e) {
string[] result = input1.Text.Split(Oprator);
//TODO: it may appear, that you want TryParse here as well
decimal value1 = decimal.Parse(result[0]);
decimal value2;
// If you have too few items, and thus you have no "value2" - do nothing
if (result.Length < 2)
return;
// Try parse result[1] to decimal; if parse fails (e.g. result[1] == "zzz") - do nothing
if (!decimal.TryParse(result[1], out value2))
return;
// you have value1, value2, Oprator; put required logic here
switch (Oprator) {
...
}
}
Have you thought about a "While" loop?
int n = 1;
while (n < 6)
{
Console.WriteLine("Current value of n is {0}", n);
n++;
}
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