Search Results

Search found 15634 results on 626 pages for 'foreach loop container'.

Page 5/626 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Foreach loop and tasks.

    - by Scott Chamberlain
    I know from the codeing guidlines that I have read you should not do for (int i = 0; i < 5; i++) { Task.Factory.StartNew(() => Console.WriteLine(i)); } Console.ReadLine(); as it will write 5 5's, I understand that and I think i understand why it is happening. I know the solution is just to do for (int i = 0; i < 5; i++) { int localI = i; Task.Factory.StartNew(() => Console.WriteLine(localI)); } Console.ReadLine(); However is something like this ok to do? foreach (MyClass myClass in myClassList) { Task.Factory.StartNew(() => myClass.DoAction()); } Console.ReadLine(); Or do I need to do the same thing I did in the for loop. foreach (MyClass myClass in myClassList) { MyClass localMyClass = myClass; Task.Factory.StartNew(() => localMyClass.DoAction()); } Console.ReadLine();

    Read the article

  • Generating new tasks in a foreach loop

    - by Scott Chamberlain
    I know from the codeing guidlines that I have read you should not do for (int i = 0; i < 5; i++) { Task.Factory.StartNew(() => Console.WriteLine(i)); } Console.ReadLine(); as it will write 5 5's, I understand that and I think i understand why it is happening. I know the solution is just to do for (int i = 0; i < 5; i++) { int localI = i; Task.Factory.StartNew(() => Console.WriteLine(localI)); } Console.ReadLine(); However is something like this ok to do? Task currentTask = myFirstTask; currentTask.Start(); foreach (Task task in _TaskList) { currentTask.ContinueWith((antecendent) => { if(antecendent.IsCompleated) { task.Start(); } else //do error handling; }); currentTask = task; } } or do i need to do this? Task currentTask = myFirstTask; foreach (Task task in _TaskList) { Task localTask = task; currentTask.ContinueWith((antecendent) => { if(antecendent.IsCompleated) { localTask.Start(); } else //do error handling; }); currentTask = task; }

    Read the article

  • php in_array() inside a foreach

    - by 432skronker
    I am having issues with using in_array() inside a foreach loop. Not sure if this is even possible or if I am doing something ridiculous where there are better ways. What I want to do is go through all the items and if their item id matches one thats in the array, return true and add the price of the item to a runninng total. $price = 0; $result = false; $array = array(1533, 2343, 2333); foreach($order['items'] as $item){ if(in_array($item['Item'], $array)){ $result = true; $price += $item['Price']; } } **UPDATED** Here is the order array [items] => Array ( [0] => Array ( [Item] => 139957 [OrderID] => 16025 [SizeID] => 24 [Price] => 46.00 ) [1] => Array ( [Item] => 2343 [OrderID] => 16025 [SizeID] => 12 [Price] => 32.00 ) ) [data] => Array ( )

    Read the article

  • WPF: How to autosize Path to its container?

    - by 742
    I have a Path that must resize to its StackPanel container. <StackPanel x:Name="TrackSurface"> <Path Fill="AliceBlue" Stroke="Black" StrokeThickness="1" Data="{StaticResource TranslateZ}"> </Path> </StackPanel> I think about using a transformation bound to the container but don't know how to it actually. Can someone give me hint?

    Read the article

  • IOC Container Handling State Params in Non-Default Constructor

    - by Mystagogue
    For the purpose of this discussion, there are two kinds of parameters an object constructor might take: state dependency or service dependency. Supplying a service dependency with an IOC container is easy: DI takes over. But in contrast, state dependencies are usually only known to the client. That is, the object requestor. It turns out that having a client supply the state params through an IOC Container is quite painful. I will show several different ways to do this, all of which have big problems, and ask the community if there is another option I'm missing. Let's begin: Before I added an IOC container to my project code, I started with a class like this: class Foobar { //parameters are state dependencies, not service dependencies public Foobar(string alpha, int omega){...}; //...other stuff } I decide to add a Logger service depdendency to the Foobar class, which perhaps I'll provide through DI: class Foobar { public Foobar(string alpha, int omega, ILogger log){...}; //...other stuff } But then I'm also told I need to make class Foobar itself "swappable." That is, I'm required to service-locate a Foobar instance. I add a new interface into the mix: class Foobar : IFoobar { public Foobar(string alpha, int omega, ILogger log){...}; //...other stuff } When I make the service locator call, it will DI the ILogger service dependency for me. Unfortunately the same is not true of the state dependencies Alpha and Omega. Some containers offer a syntax to address this: //Unity 2.0 pseudo-ish code: myContainer.Resolve<IFoobar>( new parameterOverride[] { {"alpha", "one"}, {"omega",2} } ); I like the feature, but I don't like that it is untyped and not evident to the developer what parameters must be passed (via intellisense, etc). So I look at another solution: //This is a "boiler plate" heavy approach! class Foobar : IFoobar { public Foobar (string alpha, int omega){...}; //...stuff } class FoobarFactory : IFoobarFactory { public IFoobar IFoobarFactory.Create(string alpha, int omega){ return new Foobar(alpha, omega); } } //fetch it... myContainer.Resolve<IFoobarFactory>().Create("one", 2); The above solves the type-safety and intellisense problem, but it (1) forced class Foobar to fetch an ILogger through a service locator rather than DI and (2) it requires me to make a bunch of boiler-plate (XXXFactory, IXXXFactory) for all varieties of Foobar implementations I might use. Should I decide to go with a pure service locator approach, it may not be a problem. But I still can't stand all the boiler-plate needed to make this work. So then I try this: //code named "concrete creator" class Foobar : IFoobar { public Foobar(string alpha, int omega, ILogger log){...}; static IFoobar Create(string alpha, int omega){ //unity 2.0 pseudo-ish code. Assume a common //service locator, or singleton holds the container... return Container.Resolve<IFoobar>( new parameterOverride[] {{"alpha", alpha},{"omega", omega} } ); } //Get my instance: Foobar.Create("alpha",2); I actually don't mind that I'm using the concrete "Foobar" class to create an IFoobar. It represents a base concept that I don't expect to change in my code. I also don't mind the lack of type-safety in the static "Create", because it is now encapsulated. My intellisense is working too! Any concrete instance made this way will ignore the supplied state params if they don't apply (a Unity 2.0 behavior). Perhaps a different concrete implementation "FooFoobar" might have a formal arg name mismatch, but I'm still pretty happy with it. But the big problem with this approach is that it only works effectively with Unity 2.0 (a mismatched parameter in Structure Map will throw an exception). So it is good only if I stay with Unity. The problem is, I'm beginning to like Structure Map a lot more. So now I go onto yet another option: class Foobar : IFoobar, IFoobarInit { public Foobar(ILogger log){...}; public IFoobar IFoobarInit.Initialize(string alpha, int omega){ this.alpha = alpha; this.omega = omega; return this; } } //now create it... IFoobar foo = myContainer.resolve<IFoobarInit>().Initialize("one", 2) Now with this I've got a somewhat nice compromise with the other approaches: (1) My arguments are type-safe / intellisense aware (2) I have a choice of fetching the ILogger via DI (shown above) or service locator, (3) there is no need to make one or more seperate concrete FoobarFactory classes (contrast with the verbose "boiler-plate" example code earlier), and (4) it reasonably upholds the principle "make interfaces easy to use correctly, and hard to use incorrectly." At least it arguably is no worse than the alternatives previously discussed. One acceptance barrier yet remains: I also want to apply "design by contract." Every sample I presented was intentionally favoring constructor injection (for state dependencies) because I want to preserve "invariant" support as most commonly practiced. Namely, the invariant is established when the constructor completes. In the sample above, the invarient is not established when object construction completes. As long as I'm doing home-grown "design by contract" I could just tell developers not to test the invariant until the Initialize(...) method is called. But more to the point, when .net 4.0 comes out I want to use its "code contract" support for design by contract. From what I read, it will not be compatible with this last approach. Curses! Of course it also occurs to me that my entire philosophy is off. Perhaps I'd be told that conjuring a Foobar : IFoobar via a service locator implies that it is a service - and services only have other service dependencies, they don't have state dependencies (such as the Alpha and Omega of these examples). I'm open to listening to such philosophical matters as well, but I'd also like to know what semi-authorative reference to read that would steer me down that thought path. So now I turn it to the community. What approach should I consider that I havn't yet? Must I really believe I've exhausted my options?

    Read the article

  • MonoTouch - foreach vs for loops (performance)

    - by ifwdev
    Normally I'm well aware that a consideration like this is premature optimization. Right now I have some event handlers being attached inside a foreach loop. I am wondering if this style might be prone to leaks or inefficient memory use due to closures being created. Is there any validity to this thinking?

    Read the article

  • foreach: how to iterate this

    - by ilnur777
    object(stdClass)[1] public 'inbox' => array 0 => object(stdClass)[2] public 'from' => string '55512351' (length=8) public 'date' => string '29/03/2010' (length=10) public 'time' => string '21:24:10' (length=8) public 'utcOffsetSeconds' => int 3600 public 'recipients' => array 0 => object(stdClass)[3] public 'address' => string '55512351' (length=8) public 'name' => string '55512351' (length=8) public 'deliveryStatus' => string 'notRequested' (length=12) public 'body' => string 'This is message text.' (length=21) 1 => object(stdClass)[4] public 'from' => string '55512351' (length=8) public 'date' => string '29/03/2010' (length=10) public 'time' => string '21:24:12' (length=8) public 'utcOffsetSeconds' => int 3600 public 'recipients' => array 0 => object(stdClass)[5] public 'address' => string '55512351' (length=8) public 'name' => string '55512351' (length=8) public 'deliveryStatus' => string 'notRequested' (length=12) public 'body' => string 'This is message text.' (length=21) .... .... I have this foreach, but it does not iterate address, name, deliveryStatus! Could you show how to get this data? foreach ($data->inbox as $note) { echo '<p>'; echo 'From : ' . htmlspecialchars($note->from) . '<br />'; echo 'Date : ' . htmlspecialchars($note->date) . '<br />'; echo 'Time : ' . htmlspecialchars($note->time) . '<br />'; echo 'Body : ' . htmlspecialchars($note->body) . '<br />'; }

    Read the article

  • php foreach getting values from an array

    - by sea_1987
    I am having trouble accessing the values in an array, the array looks like this, Array ( [0] => Array ( [id] => 1661 [code] => 849651318 [job_status] => 4 [looking_for] => Lorem ipsum [keywords_education] => Derby University [sector_id_csv] => 10,21,9,22,26 [last_job_title_1] => Programmer [last_job_employer_1] => HBOS [city] => Bury [expected_salary_level] => LEVEL_2 [education_level] => COLLEGE [job_looking_for] => [is_contract] => Y [is_permanent] => N [is_temporary] => Y ) ) Array ( [0] => Array ( [id] => 402 [code] => 849650059 [job_status] => 3 [looking_for] => Lorem ipsum [keywords_education] => Paris College [sector_id_csv] => 27,22,19,21,12 [last_job_title_1] => Programmer [last_job_employer_1] => HSBC [city] => Bury [expected_salary_level] => LEVEL_2 [education_level] => COLLEGE [job_looking_for] => [is_contract] => N [is_permanent] => Y [is_temporary] => Y ) ) Array ( [0] => Array ( [id] => 1653 [code] => 849651310 [job_status] => 3 [looking_for] => Lorem ipsum [keywords_education] => Crewe University [sector_id_csv] => 27,15,19,21,24 [last_job_title_1] => Programmer [last_job_employer_1] => ICI [city] => Bury [expected_salary_level] => LEVEL_2 [education_level] => UNIVERSITY [job_looking_for] => [is_contract] => N [is_permanent] => Y [is_temporary] => Y ) ) I am trying to get the values out, I have tried doing the following, foreach ($result as $rslt) { echo $rslt->id; } I have also tried, foreach ($result as $rslt) { $rslt['id']; } But none of this works, I dont know why, can anyone help?

    Read the article

  • C# - Does foreach() iterate by reference?

    - by sharkin
    Consider this: List<MyClass> obj_list = get_the_list(); foreach( MyClass obj in obj_list ) { obj.property = 42; } Is 'obj' a reference to the corresponding object within the list so that when I change the property the change will persist in the object instance once constructed somewhere?

    Read the article

  • Combining foreach and using

    - by apoorv020
    I'm iterating over a ManageObjectCollection.( which is part of WMI interface). However the important thing is, the following line of code. : foreach (ManagementObject result in results) { //code here } The point is that ManageObject also implements IDisposable, so I would like to put "result" variable in a using block. Any idea on how to do this, without getting too weird or complex?

    Read the article

  • Javascript For-Each Loop Syntax Help

    - by radrew
    Hey guys, I've got a complex block of PHP/Javascript that isn't functioning. I'm trying to manipulate a form that contains 4 dropdown select lists. Each dropdown is dependent upon what was selected in the one above it. I apologize for the huge amount of code, but I was hoping someone might be able to spot a syntax error or something else simple that I'm missing. The form in question is located in the right sidebar of the following site: http://www.buyautocovers.com $Manufacturer_array[] = array('id' => 'all', 'text' => $this->__('Choose Make')); $Model_array[] = array('id' = 'all', 'text' = $this-('Choose Model')); $Number_array[] = array('id' = 'all', 'text' = $this-('Choose Year')); $Body_array[] = array('id' = 'all', 'text' = $this-__('Choose Body Type')); $javascript = ' // var a = new Array(); var b = new Array(); var c = new Array(); var d = new Array();'; $M_a = array(); foreach ($rows as $r) { if (!isset($M_a [$r['manufacturer']])) $Manufacturer_array[] = array('id' = $r['manufacturer'], 'text' = $r['manufacturer']); $M_a [$r['manufacturer']][$r['model']][$r['number']][$r['body']] = 1; } $i = 0; foreach ($M_a as $k =$v){ $javascript .= 'a['.$i.']="'.$k.'";b['.$i.'];c['.$i.'];=new Array('; $ii = 0; $s = ''; foreach ($M_a[$k] as $kk =$vv){ $javascript .= ($ii != 0 ? ',' : '').'"'.$kk.'"'; $ss = ''; $iii = 0; foreach ($M_a[$k][$kk] as $kkk = $vvv){ $javascript .= ($iii != 0 ? ',' : '').'"'.$kkk.'"'; $sss = ''; $iiii = 0; foreach ($M_a[$k][$kk][$kkk] as $kkkk = $vvvv){ $sss .= ($iiii != 0 ? ',' : '').'"'.$kkkk.'"'; $iiii++; } $ss .= 'd['.$i.']['.$ii.']['.$iii.']=new Array('.$sss.');'; $iii++; } $s .= 'd['.$i.']['.$ii.']=new Array('.$ss.');'; $ii++; } $javascript .= ');d['.$i.']=new Array();'.$s; $i++; } $javascript .= ' function pop_model(){ var o ="' . $this-('Choose Model') . '"; var sv = $(\'mmn_manufacturer\').value; if(sv != "all"){ var v = a.length; while(v--) if(sv == a[v]) break; for(var i = 0; i < b[v].length; i++) o+=""+b[v][i]+""; } o+=""; $(\'model_select\').innerHTML= o; $(\'number_select\').innerHTML= "' . $this-('Choose Year') . '"; } function pop_number(){ var o ="' . $this-('Choose Year') . '"; var sv = $(\'mmn_manufacturer\').value; if(sv != "all"){ var v = a.length; while(v--) if(sv == a[v]) break; var sv2 = $(\'mmn_model\').value; if(sv2 != "all"){ var v2 = b[v].length; while(v2--) if(sv2 == b[v][v2]) break; for(var i = 0; i < c[v][v2].length; i++) o+=""+c[v][v2][i]+""; } } o+=""; $(\'number_select\').innerHTML= o; $(\'body_select\').innerHTML= "' . $this-('Choose Body Type') . '"; } function pop_body(){ var o ="' . $this-__('Choose Body Type') . '"; var sv = $(\'mmn_manufacturer\').value; if(sv != "all"){ var v = a.length; while(v--) if(sv == a[v]) break; var sv2 = $(\'mmn_model\').value; if(sv2 != "all"){ var v2 = b[v].length; while(v2--) if(sv2 == b[v][v2]) break; var sv3 = $(\'mmn_number\').value; if(sv3 != "all"){ var v3 = c[v].length; while(v3--) if(sv3 == b[v]c[v2][v3]) break; for(var i = 0; i < d[v]c[v2][v3].length; i++) o+=""+d[v]c[v2][v3][i]+""; } } } o+=""; $(\'number_select\').innerHTML= o; } //]] '; $expire = time()+60*60*24*90; if (isset($_GET['Manufacturer'])){ setcookie("Manufacturer_selected", $_GET['Manufacturer'], $expire,'/'); if ($_GET['Manufacturer'] != 'all') $Manufacturer_selected_var = $_GET['Manufacturer']; } elseif (isset($_COOKIE['Manufacturer_selected']) && $_COOKIE['Manufacturer_selected'] != 'all') $Manufacturer_selected_var = $_COOKIE['Manufacturer_selected']; if (isset($_GET['Model'])){ setcookie("Model_selected", $_GET['Model'], $expire,'/'); if ($_GET['Model'] != 'all') $Model_selected_var = $_GET['Model']; } elseif (isset($_COOKIE['Model_selected']) && $_COOKIE['Model_selected'] != 'all') $Model_selected_var = $_COOKIE['Model_selected']; if (isset($_GET['Number'])){ setcookie("Number_selected", $_GET['Number'], $expire,'/'); if ($_GET['Number'] != 'all') $Number_selected_var = $_GET['Number']; } elseif (isset($_COOKIE['Number_selected']) && $_COOKIE['Number_selected'] != 'all') $Number_selected_var = $_COOKIE['Number_selected']; if (isset($_GET['Body'])){ setcookie("Body_selected", $_GET['Body'], $expire,'/'); if ($_GET['Body'] != 'all') $Body_selected_var = $_GET['Body']; } elseif (isset($_COOKIE['Body_selected']) && $_COOKIE['Body_selected'] != 'all') $Body_selected_var = $_COOKIE['Body_selected']; if (isset($Manufacturer_selected_var) && isset($M_a[$Manufacturer_selected_var])) foreach ($M_a[$Manufacturer_selected_var] as $k => $v) $Model_array[] = array('id' = $k, 'text' = $k); if (isset($Manufacturer_selected_var) && isset($Model_selected_var) && isset($M_a[$Manufacturer_selected_var][$Model_selected_var])) foreach ($M_a[$Manufacturer_selected_var][$Model_selected_var] as $k = $v) $Number_array[] = array('id' = $k, 'text' = $k); if (isset($Manufacturer_selected_var) && isset($Model_selected_var) && isset($Number_selected_var) && isset($M_a[$Manufacturer_selected_var][$Model_selected_var][$Number_selected_var])) foreach ($M_a[$Manufacturer_selected_var][$Model_selected_var][$Number_selected_var] as $k = $v) $Body_array[] = array('id' = $k, 'text' = $k); echo $javascript;

    Read the article

  • The IOC "child" container / Service Locator

    - by Mystagogue
    DISCLAIMER: I know there is debate between DI and service locator patterns. I have a question that is intended to avoid the debate. This question is for the service locator fans, who happen to think like Fowler "DI...is hard to understand...on the whole I prefer to avoid it unless I need it." For the purposes of my question, I must avoid DI (reasons intentionally not given), so I'm not trying to spark a debate unrelated to my question. QUESTION: The only issue I might see with keeping my IOC container in a singleton (remember my disclaimer above), is with the use of child containers. Presumably the child containers would not themselves be singletons. At first I thought that poses a real problem. But as I thought about it, I began to think that is precisely the behavior I want (the child containers are not singletons, and can be Disposed() at will). Then my thoughts went further into a philosophical realm. Because I'm a service locator fan, I'm wondering just how necessary the notion of a child container is in the first place. In a small set of cases where I've seen the usefulness, it has either been to satisfy DI (which I'm mostly avoiding anyway), or the issue was solvable without recourse to the IOC container. My thoughts were partly inspired by the IServiceLocator interface which doesn't even bother to list a "GetChildContainer" method. So my question is just that: if you are a service locator fan, have you found that child containers are usually moot? Otherwise, when have they been essential? extra credit: If there are other philosophical issues with service locator in a singleton (aside from those posed by DI advocates), what are they?

    Read the article

  • Calling DI Container directly in method code (MVC Actions)

    - by fearofawhackplanet
    I'm playing with DI (using Unity). I've learned how to do Constructor and Property injection. I have a static container exposed through a property in my Global.asax file (MvcApplication class). I have a need for a number of different objects in my Controller. It doesn't seem right to inject these throught the constructor, partly because of the high quantity of them, and partly because they are only needed in some Actions methods. The question is, is there anything wrong with just calling my container directly from within the Action methods? public ActionResult Foo() { IBar bar = (Bar)MvcApplication.Container.Resolve(IBar); // ... Bar uses a default constructor, I'm not actually doing any // injection here, I'm just telling my conatiner to give me Bar // when I ask for IBar so I can hide the existence of the concrete // Bar from my Controller. } This seems the simplest and most efficient way of doing things, but I've never seen an example used in this way. Is there anything wrong with this? Am I missing the concept in some way?

    Read the article

  • Proper method to update and draw from game loop?

    - by Lost_Soul
    Recently I've took up the challenge for myself to create a basic 2d side scrolling monster truck game for my little brother. Which seems easy enough in theory. After working with XNA it seems strange jumping into Java (which is what I plan to program it in). Inside my game class I created a private class called GameLoop that extends from Runnable, then in the overridden run() method I made a while loop that handles time and such and I implemented a targetFPS for drawing as well. The loop looks like this: @Override public void run() { long fpsTime = 0; gameStart = System.currentTimeMillis(); lastTime = System.currentTimeMillis(); while(game.isGameRunning()) { currentTime = System.currentTimeMillis(); long ellapsedTime = currentTime - lastTime; if(mouseState.leftIsDown) { que.add(new Dot(mouseState.getPosition())); } entities.addAll(que); game.updateGame(ellapsedTime); fpsTime += ellapsedTime; if(fpsTime >= (1000 / targetedFPS)) { game.drawGame(ellapsedTime); } lastTime = currentTime; } The problem I've ran into is adding of entities after a click. I made a class that has another private class that extends MouseListener and MouseMotionListener then on changes I have it set a few booleans to tell me if the mouse is pressed or not which seems to work great but when I add the entity it throws a CME (Concurrent Modification Exception) sometimes. I have all the entities stored in a LinkedList so later I tried adding a que linkedlist where I later add the que to the normal list in the update loop. I think this would work fine if it was just the update method in the gameloop but with the repaint() method (called inside game.drawGame() method) it throws the CME. The only other thing is that I'm currently drawing directly from the overridden paintComponent() method in a custom class that extends JPanel. Maybe there is a better way to go about this? As well as fix my CME? Thanks in advance!!!

    Read the article

  • An observation on .NET loops – foreach, for, while, do-while

    It’s very common that .NET programmers use “foreach” loop for iterating through collections. Following is my observation whilst I was testing simple scenario on loops. “for” loop is 30% faster than “foreach” and “while” loop is 50% faster than “foreach”. “do-while” is bit faster than “while”. Someone may feel that how does it make difference if I’m iterating only 1000 times in a loop. This test case is only for simple iteration. According to the "Data structure" concepts, best and worst cases are completely based on the data we provide to the algorithm. so we can not conclude that a "foreach" algorithm is not good. All I want to tell that we need to be little cautious even choosing the loops. Example:- You might want to chose quick sort when you want to sort more numbers. At the same time bubble sort may be effective than quick sort when you want to sort less numbers. Take a simple scenario, a request of a simple web application fetches the data of 10000 (10K) rows and iterating them for some business logic. Think, this application is being accessed by 1000 (1K) people simultaneously. In this simple scenario you are ending up with 10000000 (10Million or 1 Crore) iterations. below is the test scenario with simple console application to test 100 Million records. using System;using System.Collections.Generic;using System.Diagnostics;namespace ConsoleApplication1{ class Program { static void Main(string[] args) { var sw = new Stopwatch(); var numbers = GetSomeNumbers(); sw.Start(); foreach (var item in numbers) { } sw.Stop(); Console.WriteLine( String.Format("\"foreach\" took {0} milliseconds", sw.ElapsedMilliseconds)); sw.Reset(); sw.Start(); for (int i = 0; i < numbers.Count; i++) { } sw.Stop(); Console.WriteLine( String.Format("\"for\" loop took {0} milliseconds", sw.ElapsedMilliseconds)); sw.Reset(); sw.Start(); var it = 0; while (it++ < numbers.Count) { } sw.Stop(); Console.WriteLine( String.Format("\"while\" loop took {0} milliseconds", sw.ElapsedMilliseconds)); sw.Reset(); sw.Start(); var it2 = 0; do { } while (it2++ < numbers.Count); sw.Stop(); Console.WriteLine( String.Format("\"do-while\" loop took {0} milliseconds", sw.ElapsedMilliseconds)); } #region Get me 10Crore (100 Million) numbers private static List<int> GetSomeNumbers() { var lstNumbers = new List<int>(); var count = 100000000; for (var i = 1; i <= count; i++) { lstNumbers.Add(i); } return lstNumbers; } #endregion Get me some numbers }} In above example, I was just iterating through 100 Million numbers. You can see the time to execute various  loops provided in .NET Output "foreach" took 1108 milliseconds "for" loop took 727 milliseconds "while" loop took 596 milliseconds "do-while" loop took 594 milliseconds   Press any key to continue . . . So I feel we need to be careful while choosing the looping strategy. Please comment your thoughts. span.fullpost {display:none;}

    Read the article

  • reuse div container to load images

    - by user295927
    Hi All; What I would like to do: use a single container to load images. As it is now: I have eleven (11) containers in HTML mark-up each with its own div. each container holds 4 images (2 images side by side top and bottom) when link in anchor tag is clicked div with images fades in. /*-- Jquery accordion is used for navigation typical example is below --*/ <li> <a class="head" href="#">commercial/hospitality</a> <ul> <li><a href="#" projectName="project1" projectType="hospitality1" image1="images/testImage1.jpg" image2="images/testImage2.jpg" image3="images/testImage3.jpg" image4="images/testImage4.jpg">hospitality project number 1</a> </li> <li><a href="#" projectName="project2" projectType="hospitality2" image1="images/testImage1.jpg" image2="images/testImage2.jpg" image3="images/testImage3.jpg" image4="images/testImage4.jpg">hospitality project number 2</a> </li> <li><a href="#" projectName="project3" projectType="hospitality3" image1="images/testImage1.jpg" image2="images/testImage2.jpg" image3="images/testImage3.jpg" image4="images/testImage4.jpg">hospitality project number 3</a> </li> </ul> </li> Typical <div> container used for image insertion currently there are 11 of them: <div id="hospitality1" class="current"> <div id="image1"><img src="images/testImage.jpg"/></div> <div id="image2"><img src="images/testImage.jpg"/></div> <div id="image3"><img src="images/testImage.jpg"/></div> <div id="image4"><img src="images/testImage.jpg"/></div> </div> Here is the code I am using at this point, it does work, but is there a better way to do this that will only re-use a single div container for loading the images? $(document).ready(function(){ $('#navigation a').click(function (selected) { var projectType = $(this).attr("projectType"); //projectType var projectName = $(this).attr("projectName"); //projectName var image1 = $(this).attr("image1"); //anchor tag for image number 1 var image2 = $(this).attr("image2"); //anchor tag for image number 2 var image3 = $(this).attr("image3"); //anchor tag for image number 3 var image4 = $(this).attr("image4"); //anchor tag for image number 4 console.log(projectType); //returns type of project console.log(projectName); //returns name of project console.log(image1); //returns 1st image console.log(image2); //returns 2nd image console.log(image3); //returns 3rd image console.log(image4); //returns 4th image $(function() { $(".current").hide(); // hides previous selected image $("#" + projectType ).fadeIn("normal").addClass("current"); }); }); As you can, see the mark up getting quite large. Any help is appreciated. ussteele

    Read the article

  • question about select() and range of for loop to read sockets

    - by Fantastic Fourier
    Just a quick question about using select(). I'm using select() to read from multiple sockets. When I looked up examples on how to use select(), a lot of tutorials showed going through for loops and checking for FD_ISSET. The problem I have with those tutorials is that the for loop starts from i = 0. and checks if the bit has been set for the file descriptor i using FD_ISSET. Couldn't the for loop start from say your minfd (just like how you would keep track of maxfd)?? Or am I missing something?? Following link is an example of such for loop (look at the fourth example that he gives) http://www.developerweb.net/forum/showthread.php?t=2933 If that was the only example out there that used such for loop, I might understand it was a mistake or bad coding but I've seen several examples of such for loop of uselessly going through literally thousands of sockets and I'm convinced I'm missing something. Any comments or inputs are appreciated.

    Read the article

  • Generic foreach loop in C#.

    - by mcoolbeth
    The compiler, given the following code, tells me "Use of unassigned local variable 'x'." Any thoughts? public delegate Y Function<X,Y>(X x); public class Map<X,Y> { private Function<X,Y> F; public Map(Function f) { F = f; } public Collection<Y> Over(Collection<X> xs){ List<Y> ys = new List<Y>(); foreach (X x in xs) { X x2 = x;//ys.Add(F(x)); } return ys; } }

    Read the article

  • Removing last word from FOREACH loop

    - by Stoosh
    I'm building a basic function, which builds out Mysql WHERE clauses based on how many are in the array. $array = array('id' => '3', 'name' => 'roger'); $sql = "SELECT * FROM table WHERE "; foreach ($array as $k => $v) { $sql .= $k . ' = ' . $v . ' AND '; } which will output SELECT * FROM table WHERE id = 3 AND name = roger AND However obviously I don't want that last AND, how do I go about removing it from the string? Thanks

    Read the article

  • Foreach loop is running n times

    - by Furqan Khyraj
    foreach($CarAdList as $CarAd) { echo($msg .= '<tr><td>'.$CarAd->getCarAdID().'</td><td>' .$CarAd->getBrandText().'</td><td>' .$CarAd->getDescription(). '</td><td><a href="status.php?id='.$CarAd->getCarAdID().'"><img src="../images/active.png" /></a></td><td><img src="../images/delete.png" width="30px" /></td></tr>'); } e.g, the number of rows =38 n= the number of rows * the number of rows-- it is running n times so its displaying 5 5 4 5 4 3 5 4 3 2 5 4 3 2 1

    Read the article

  • Foreach File in a Folder in Flash?

    - by msandbot
    Hey, I have an image slideshow program working right now and it takes in a folder of a hard coded in number of images. I would like to change this so that it can take in a folder and will display all of them no matter the number. Is there a way to do this in flash? I'm thinking something like the foreach loop in perl or other scripting language. It is possible to store then number of images in a text file but I also don't know how to read that in flash either. I'm working in actionscript 3. Any help would be greatly appreciated. Thanks -Mike

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >