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 9 years ago.
Improve this question
By seeing this solution specified in Divide Foreach into threads sample
I tried to implement it with this code:
foreach (Object vo in arrreclist)
{
msg = String.Empty;
objprocess.GetType().GetMethod("ProcessRecord").Invoke(objprocess, new Object[] { vo });
status = (StatusInfo)objprocess.GetType().GetProperty("status").GetValue(objprocess, null);
if (status.errcode != 0)
{
lngfailedcnt++;
WriteErrorLog();
}
else
{
lngsuccesscnt++;
lngInstanceSuccCount++;
}
lngcnt++;
if ((lngcnt % 10) == 0)
{
if (instanceId == 0)
{
schldr.ModifyJobhistoryForUploadFileRecCnt(Runid, (int)lngTotreccnt, lngfailedcnt, (int)(lngfailedcnt + lngsuccesscnt));
}
else
{
schldr.ModifyJobhistoryForUploadFileRecCnt(Runid, 0, lngfailedcnt, (int)(lngfailedcnt + lngsuccesscnt));
}
status = schldr.status;
if (status.errcode != 0)
{
if (!String.IsNullOrEmpty(Errorlogfile))
WriteErrorLog();
holdInstance = true;
break;
}
//Get Job Status
//If job was terminated then Update Batch and Job history with status as STOPPED
intstatus = schedulersvc.GetJobStatus(Runid);
status = schedulersvc.status;
if (status.errcode != 0)
{
WriteErrorLog();
holdInstance = true;
break;
}
if (intstatus == 1) //STOPPED
{
holdInstance = true;
break;
}
lngcnt = 0;
}
}
And error message is coming for break statement:
cannot leave the body of anonymous method or lambda expression
My major task is to parallelize the following line:
objprocess.GetType().GetMethod("ProcessRecord").Invoke(objprocess, new Object[] { vo })
But other are dependents so how to implement?
First, parallelization often doesn't make sense in ASP.NET. If you have many users accessing your site, you usually care more about scalability (how many users can you serve at the same time), than raw performance for single user.
If that's not your case, parallelization might make sense for you.
Second, you're getting that error, because Parallel.ForEach() is not a loop (as far as the language is concerned). And breaking out of a lambda doesn't make any sense.
To break out of Parallel.ForEach(), you can use ParallelLoopState.Break() or ParallelLoopState.Stop() (read the documentation to find out which one of those do you actually want). To do this, you will need to use an overload of Parallel.ForEach() that gives you that ParallelLoopState.
Third, there is a good reason why Parallel.ForEach() doesn't support ArrayList: it's because you should never use it. If you really want a list of objects, use List<object> to make it clear that you really don't know the type. If you can't (or don't want to) change the ArrayList, you can use .Cast<object>() to make Parallel.ForEach() (and other methods that work with IEnumerable<T>) accept it.
Fourth, I think that parallelizing just the ProcessRecord doesn't make sense. It looks like status returns the status for the last ProcessRecord. And if you execute ProcessRecord in parallel, then it's not clear anymore which one is the last.
Also, you shouldn't think that some method is not thread-safe. You should know that. If you parallelize something that you don't know is thread-safe, you're likely to get hard to debug bugs later on.
Fifth, if you want to parallelize just the first part of a loop, I think the best option is PLINQ. Something like:
var intermediateResults = source.AsParallel().Select(x => Process(x));
foreach (var intermediateResult in intermediateResults)
{
// the rest of the loop
}
Related
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 4 months ago.
Improve this question
menu2:
WriteLine("New category");
WriteLine("***************************");
WriteLine();
Write("Name: ");
string categoryName = ReadLine();
WriteLine("Is this correct? (Y)es (N)o");
Category category = new Category(categoryName);
do
{
userInput = ReadKey(true);
invalidSelection = !(userInput.Key == ConsoleKey.Y ||
userInput.Key == ConsoleKey.N);
}
while (invalidSelection);
var categoryExist = categoryList.Any(x => x.CategoryName == categoryName);
switch (userInput.Key)
{
case ConsoleKey.Y:
{
if (!categoryExist)
{
categoryList.Add(category);
Clear();
WriteLine("Category created!");
Thread.Sleep(2000);
}
else
{
Clear();
WriteLine("Category already exist");
Thread.Sleep(2000);
Clear();
}
break;
}
case ConsoleKey.N:
Clear();
goto menu2;
}
break;
I'm kinda new to programming and I've realized that people reaaalllyy don't like "goto"-methods. What else can i use? For example, in the code, the user inputs a category, and is then asked wether he/she typed in the category name correctly if YES then we add it if NO then u jump back to Name and have to type it in one more time. How could I do this without having to use go-to method?
You already use the same thing in your code - a do-while loop will do nicely.
It also helps to separate your code into logical blocks "hidden" in methods. That can help the readability of code like this, where you have distinct menus - instead of having a long block of code with multiple gotos, you can keep each level of the menu as its own method, and each call can be surrounded by a loop (or the method itself, depending on your preference).
Methods also give you the option to use return, which in many similar cases serves as a good replacement for goto-using code.
As you get deeper into understanding C#, new options for simplification and/or abstraction open up. For example, you can replace multiple occurrences of the same (logical) loop with functions or classes/interfaces. No rush, though :)
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 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 4 years ago.
Improve this question
I am using C# with the Selenium Webdriver. I want to break the loop if the 'if' condition isn't met. My code is below. If the 'if' condition is met I want to continue the loop until it isn't.
for (int i = 0; i < Numara.Items.Count; i++)
{
driveri.Navigate().GoToUrl("https://web.whatsapp.com/send?phone=" + Numara.Items[i].ToString() + "&text=");
Thread.Sleep(3000);
Actions act = new Actions(driveri);
Thread.Sleep(500);
IReadOnlyCollection<IWebElement> rows = driveri.FindElements(By.XPath("//*[#id=\"app\"]/div/span[3]/div/div/div/div/div/div/div[2]/div"));
if (rows == null)
{
...continuation
}
else
{
...if there is an error
rows.ElementAt(0).Click();
}
}
}
This is what you are asking for
if (rows == null)
{
continue;
}
else
{
rows.ElementAt(0).Click();
break;
}
However it'd be better code practice and more efficient to use a while loop implementation instead;
IReadOnlyCollection<IWebElement> rows = null;
bool rowsFound = false;
while (!rowsFound)
{
rows = driveri.FindElements(By.XPath("//*[#id=\"app\"]/div/span[3]/div/div/div/div/div/div/div[2]/div"));
if(rows!=null)
{
rowsFound = true;
}
}
rows.ElementAt(0).Click();
On an unrelated topic, it's also bad practice to be using Thread.Sleep(), unless absolutely necessary. Most, if not all the time you will want to use WebDriverWait implementation. You can find out more about that here: https://seleniumhq.github.io/selenium/docs/api/dotnet/html/T_OpenQA_Selenium_Support_UI_WebDriverWait.htm
The OP's issue description is quite confusing
I want to use selenium in c # to close the loop if it fails.
If the error comes out, I want to click on the link and continue the
loop.
If you want to end the loop immediately after encountering an error, use break.
Using continue on the other hand will skip the remaining statements and will go to the next iteration of your loop.
else
{
...if there is an error
rows.ElementAt(0).Click();
break;
}
Away from the topic though , I just noticed your Absolute XPATH usage. Using absolute is not really advisable, be better to use relative-concise and short xpath. An update to webapp, will surely break your xpath's of your script.
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 6 years ago.
Improve this question
I have two function with different functionality and i want to call them based on some value. without if else or switch case block. like i have
Dictionary<string, string> intentMap = new Dictionary<string, string>();
intentMap.Add("rootIntent", "TicketbookingInformation");
intentMap.Add("rootIntent", "OrderInformation");
and i have two function
public bool BookTicket()
{
// to do
}
public bool BookOrder()
{
// to do
}
I want to switch these function if intentMap has TicketbookingInformation then call BookTicket method or if intentMap has OrderInformation then call BookOrder method.
I want to do in generic way using deleagtes so in future if I have some more use case (new method), so i can utilize the same functionlaity without modifying much.
Use another dictionary, this time of type <string, Func<bool>:
var delegateMap = new Dictionary<string, Func<bool>>()
{
{ "TicketBookingInformation", BookTicket },
{ "OrderInformation", BookOrder }
};
foreach (var intent in intentMap)
{
bool result = delegateMap[intent.Value]();
}
I won't answer to your question directly. #Abion47 has answered perfectly fine, i would answer the same.
But i think having having two dictionaries one having the token, and another having the delegate is more obscure then having single method for dispatching the result.
Here is my point with a bit code.
This the dictionary version.
var intentMap = new Dicionary<string, string>();
var delegateMap = new Dictionary<string, Func<bool>>();
delegate.Map.Add("TicketbookingInformation", BookTicket);
delegateMap.Add("OrderInformation", BookOrder);
Then the usage will be something like this
var token = ...;
if(intentMap.ContainsKey(token))
{
var delegateToken = intenMap[token];
if(delegateMap.ContainsKey(delegateToken))
{
var delegatedMethod = delegateMap(delegateToken);
return delegatedMethod();
}
}
So adding new token and delegate will means extending the dictionaries and i can't see how this is different then extending a switch statement.
Second version which i think will be generic enough and will need not too much modification where used will be something like this.
First i will suggest having the "TicketbookingInformation" and "OrderInformation" as enumeration type, this way having a switch statement will benefit from the compiler helping when you have some missing case to handle. This of course is applicable if you know upfront all the possible values ;]
bool PredicateDispatch(DelegateToken token)
{
switch(token)
{
DelegateToken.TicketbookingInformation: return BookTicket();
DelegateToken.OrderInformation: return BookOrder()
}
}
this way you will need to extend this single method to handle new tokens. It is more readable approach and you don't lose anything compared with the dictionary version. So i will do it this way. If don't have of course more complicated code and your example is more more simplified ;]
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
}