Search Results

Search found 720 results on 29 pages for 'tolist'.

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

  • asp.net mvc 2: SportsStore application: The current request for action is ambiguous

    - by dotnet-practitioner
    I am working on SportsStore example on chapter 4 from the following book and getting stuck... Pro Asp.net mvc framework I get the following error: The current request for action 'List' on controller type 'ProductsController' is ambiguous between the following action methods: System.Web.Mvc.ViewResult List() on type WebUI.Controllers.ProductsController System.Web.Mvc.ViewResult List(Int32) on type WebUI.Controllers.ProductsController .. My router code looks as follows: public static void RegisterRoutes(RouteCollection routes) { routes.MapRoute( null, // Route name "", // URL with parameters new { controller = "Products", action = "List", page=1 } ); routes.MapRoute( null, // Route name "Page{page}", // URL with parameters new { controller = "Products", action = "List" }, // Parameter defaults new { page = @"\d+" } ); } and controller code looks as follows: public ViewResult List() { return View(productsRepository.Products.ToList()); } public ViewResult List(int page) { return View(productsRepository.Products .Skip((page - 1) * PageSize) .Take(PageSize) .ToList()); } What am I missing? my url is as follows: http://localhost:1103/ or http://localhost:1103/Page1 or http://localhost:1103/Page2 thanks

    Read the article

  • parsing expression trees with booleans

    - by Schotime
    I am trying to parse an expression tree for a linq provider and running into a little snag with booleans. I can parse this no problems. var p = products.Where(x=>x.IsAvailable == true).ToList(); however when its written like this? var p = products.Where(x=>x.IsAvailable).ToList(); i only get a MemberAccess to look at and i can't see how i deduce that it is true or false (!x.IsAvailable). Any help would be great. Thanks.

    Read the article

  • SQLiteException and SQLite error near "(": syntax error with Subsonic ActiveRecord

    - by nvuono
    I ran into an interesting error with the following LiNQ query using LiNQPad and when using Subsonic 3.0.x w/ActiveRecord within my project and wanted to share the error and resolution for anyone else who runs into it. The linq statement below is meant to group entries in the tblSystemsValues collection into their appropriate system and then extract the system with the highest ID. from ksf in KeySafetyFunction where ksf.Unit == 2 && ksf.Condition_ID == 1 join sys in tblSystems on ksf.ID equals sys.KeySafetyFunction join xval in (from t in tblSystemsValues group t by t.tblSystems_ID into groupedT select new { sysId = groupedT.Key, MaxID = groupedT.Max(g=>g.ID), MaxText = groupedT.First(gt2 => gt2.ID == groupedT.Max(g=>g.ID)).TextValue, MaxChecked = groupedT.First(gt2 => gt2.ID == groupedT.Max(g=>g.ID)).Checked }) on sys.ID equals xval.sysId select new {KSFDesc=ksf.Description, sys.Description, xval.MaxText, xval.MaxChecked} On its own, the subquery for grouping into groupedT works perfectly and the query to match up KeySafetyFunctions with their System in tblSystems also works perfectly on its own. However, when trying to run the completed query in linqpad or within my project I kept running into a SQLiteException SQLite Error Near "(" First I tried splitting the queries up within my project because I knew that I could just run a foreach loop over the results if necessary. However, I continued to receive the same exception! I eventually separated the query into three separate parts before I realized that it was the lazy execution of the queries that was killing me. It then became clear that adding the .ToList() specifier after the myProtectedSystem query below was the key to avoiding the lazy execution after combining and optimizing the query and being able to get my results despite the problems I encountered with the SQLite driver. // determine the max Text/Checked values for each system in tblSystemsValue var myProtectedValue = from t in tblSystemsValue.All() group t by t.tblSystems_ID into groupedT select new { sysId = groupedT.Key, MaxID = groupedT.Max(g => g.ID), MaxText = groupedT.First(gt2 => gt2.ID ==groupedT.Max(g => g.ID)).TextValue, MaxChecked = groupedT.First(gt2 => gt2.ID ==groupedT.Max(g => g.ID)).Checked}; // get the system description information and filter by Unit/Condition ID var myProtectedSystem = (from ksf in KeySafetyFunction.All() where ksf.Unit == 2 && ksf.Condition_ID == 1 join sys in tblSystem.All() on ksf.ID equals sys.KeySafetyFunction select new {KSFDesc = ksf.Description, sys.Description, sys.ID}).ToList(); // finally join everything together AFTER forcing execution with .ToList() var joined = from protectedSys in myProtectedSystem join protectedVal in myProtectedValue on protectedSys.ID equals protectedVal.sysId select new {protectedSys.KSFDesc, protectedSys.Description, protectedVal.MaxChecked, protectedVal.MaxText}; // print the gratifying debug results foreach(var protectedItem in joined) { System.Diagnostics.Debug.WriteLine(protectedItem.Description + ", " + protectedItem.KSFDesc + ", " + protectedItem.MaxText + ", " + protectedItem.MaxChecked); }

    Read the article

  • Order by descending based on condition

    - by Vinni
    Hello All, I want to write a LINQ to Entity query which does order by ascending or descending based on input parameter, Is there any way for that. Following is the my code. Please suggest. public List<Hosters_HostingProviderDetail> GetPendingApproval(SortOrder sortOrder) { List<Hosters_HostingProviderDetail> returnList = new List<Hosters_HostingProviderDetail>(); int pendingStateId = Convert.ToInt32(State.Pending); //If the sort order is ascending if (sortOrder == SortOrder.ASC) { var hosters = from e in context.Hosters_HostingProviderDetail where e.ActiveStatusID == pendingStateId orderby e.HostingProviderName ascending select e; returnList = hosters.ToList<Hosters_HostingProviderDetail>(); return returnList; } else { var hosters = from e in context.Hosters_HostingProviderDetail where e.StateID == pendingStateId orderby e.HostingProviderName descending select e; returnList = hosters.ToList<Hosters_HostingProviderDetail>(); return returnList; } }

    Read the article

  • c#: Clean way to fit a collection into a multidimensional array?

    - by Rosarch
    I have an ICollection<MapNode>. Each MapNode has a Position attribute, which is a Point. I want to sort these points first by Y value, then by X value, and put them in a multidimensional array (MapNode[,]). The collection would look something like this: (30, 20) (20, 20) (20, 30) (30, 10) (30, 30) (20, 10) And the final product: (20, 10) (20, 20) (20, 30) (30, 10) (30, 20) (30, 30) Here is the code I have come up with to do it. Is this hideously unreadable? I feel like it's more hacky than it needs to be. private Map createWorldPathNodes() { ICollection<MapNode> points = new HashSet<MapNode>(); Rectangle worldBounds = WorldQueryUtils.WorldBounds(); for (float x = worldBounds.Left; x < worldBounds.Right; x += PATH_NODE_CHUNK_SIZE) { for (float y = worldBounds.Y; y > worldBounds.Height; y -= PATH_NODE_CHUNK_SIZE) { // default is that everywhere is navigable; // a different function is responsible for determining the real value points.Add(new MapNode(true, new Point((int)x, (int)y))); } } int distinctXValues = points.Select(node => node.Position.X).Distinct().Count(); int distinctYValues = points.Select(node => node.Position.Y).Distinct().Count(); IList<MapNode[]> mapNodeRowsToAdd = new List<MapNode[]>(); while (points.Count > 0) // every iteration will take a row out of points { // get all the nodes with the greatest Y value currently in the collection int currentMaxY = points.Select(node => node.Position.Y).Max(); ICollection<MapNode> ythRow = points.Where(node => node.Position.Y == currentMaxY).ToList(); // remove these nodes from the pool we're picking from points = points.Where(node => ! ythRow.Contains(node)).ToList(); // ToList() is just so it is still a collection // put the nodes with max y value in the array, sorting by X value mapNodeRowsToAdd.Add(ythRow.OrderByDescending(node => node.Position.X).ToArray()); } MapNode[,] mapNodes = new MapNode[distinctXValues, distinctYValues]; int xValuesAdded = 0; int yValuesAdded = 0; foreach (MapNode[] mapNodeRow in mapNodeRowsToAdd) { xValuesAdded = 0; foreach (MapNode node in mapNodeRow) { // [y, x] may seem backwards, but mapNodes[y] == the yth row mapNodes[yValuesAdded, xValuesAdded] = node; xValuesAdded++; } yValuesAdded++; } return pathNodes; } The above function seems to work pretty well, but it hasn't been subjected to bulletproof testing yet.

    Read the article

  • The cost of nested methods

    - by Palimondo
    In Scala one might define methods inside other methods. This limits their scope of use to inside of definition block. I use them to improve readability of code that uses several higher-order functions. In contrast to anonymous function literals, this allows me to give them meaningful names before passing them on. For example: class AggregatedPerson extends HashSet[PersonRecord] { def mostFrequentName: String = { type NameCount = (String, Int) def moreFirst(a: NameCount, b: NameCount) = a._2 > b._2 def countOccurrences(nameGroup: (String, List[PersonRecord])) = (nameGroup._1, nameGroup._2.size) iterator.toList.groupBy(_.fullName). map(countOccurrences).iterator.toList. sortWith(moreFirst).head._1 } } Is there any runtime cost because of the nested method definition I should be aware of? Does the answer differ for closures?

    Read the article

  • Algorithm to retrieve every possible combination of sublists of a two lists

    - by sgmoore
    Suppose I have two lists, how do I iterate through every possible combination of every sublist, such that each item appears once and only once. I guess an example could be if you have employees and jobs and you want split them into teams, where each employee can only be in one team and each job can only be in one team. Eg List<string> employees = new List<string>() { "Adam", "Bob"} ; List<string> jobs = new List<string>() { "1", "2", "3"}; I want Adam : 1 Bob : 2 , 3 Adam : 1 , 2 Bob : 3 Adam : 1 , 3 Bob : 2 Adam : 2 Bob : 1 , 3 Adam : 2 , 3 Bob : 1 Adam : 3 Bob : 1 , 2 Adam, Bob : 1, 2, 3 I tried using the answer to this stackoverflow question to generate a list of every possible combination of employees and every possible combination of jobs and then select one item from each from each list, but that's about as far as I got. I don't know the maximum size of the lists, but it would be certainly be less than 100 and there may be other limiting factors (such as each team can have no more than 5 employees) Update Not sure whether this can be tidied up more and/or simplified, but this is what I have ended up with so far. It uses the Group algorithm supplied by Yorye (see his answer below), but I removed the orderby which I don't need and caused problems if the keys are not comparable. var employees = new List<string>() { "Adam", "Bob" } ; var jobs = new List<string>() { "1", "2", "3" }; int c= 0; foreach (int noOfTeams in Enumerable.Range(1, employees.Count)) { var hs = new HashSet<string>(); foreach( var grouping in Group(Enumerable.Range(1, noOfTeams).ToList(), employees)) { // Generate a unique key for each group to detect duplicates. var key = string.Join(":" , grouping.Select(sub => string.Join(",", sub))); if (!hs.Add(key)) continue; List<List<string>> teams = (from r in grouping select r.ToList()).ToList(); foreach (var group in Group(teams, jobs)) { foreach (var sub in group) { Console.WriteLine(String.Join(", " , sub.Key ) + " : " + string.Join(", ", sub)); } Console.WriteLine(); c++; } } } Console.WriteLine(String.Format("{0:n0} combinations for {1} employees and {2} jobs" , c , employees.Count, jobs.Count)); Since I'm not worried about the order of the results, this seems to give me what I need.

    Read the article

  • ASP.NET MVC 3 Linq uppercase or lowercase database search

    - by user1495557
    I need immediate help. ): and i know little english. ASP.NET MVC 3 Linq uppercase or lowercase contains search Example: string metin="baris"; var IcerikAra = (from icerik in Context.dbDokumanEditor join kategori in Context.dbDokumanKategori on icerik.KategoriID equals kategori.KategoriID where icerik.Icerik.toLower().Contains(metin) select new { KategoriID=kategori. KategoriAd=kategori.KategoriAd }).ToList(); Exception: StackTrace: at System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommandentityCommand, CommandBehavior behavior) at System.Data.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues) at System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) at System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable.GetEnumerator() at System.Data.Entity.Internal.Linq.InternalQuery`1.GetEnumerator() at System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable.GetEnumerator() at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source) at Plus.Areas.DokumanEditor.Controllers.DokumanController.DokumanIcerikAramaBaslat(String metin) Error Message: An error occurred while executing the command definition. See the inner exception for details. thanks..

    Read the article

  • How to overwrite specific lines on text files

    - by iTayb
    I have two text files. I'd like to copy a specific part in the first text file and replace it with a part of the second text file. This is how I read the files: List<string> PrevEp = File.ReadAllLines(string.Format(@"{0}naruto{1}.ass", url, PrevEpNum)).ToList(); List<string> Ep = File.ReadAllLines(string.Format(@"{0}naruto{1}.ass", url, EpNum)).ToList(); The part in PrevEp that I need: from the start until it meets a line that includes Creditw,,0000,0000,0000. The part I would like to overwrite in Ep: from the start to a line which is exactly Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text. I'm not so sure how may I do it. Could you lend me a hand? Thank you very much, gentlemen.

    Read the article

  • Why does LINQ-to-SQL Paging fail inside a function?

    - by ssg
    Here I have an arbitrary IEnumerable<T>. And I'd like to page it using a generic helper function instead of writing Skip/Take pairs every time. Here is my function: IEnumerable<T> GetPagedResults<T>(IEnumerable<T> query, int pageIndex, int pageSize) { return query.Skip((pageIndex - 1) * pageSize).Take(pageSize); } And my code is: result = GetPagedResults(query, 1, 10).ToList(); This produces a SELECT statement without TOP 10 keyword. But this code below produces the SELECT with it: result = query.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList(); What am I doing wrong in the function?

    Read the article

  • How to perform add/update of a model object that contains EntitySet

    - by David Liddle
    I have a similar concept to the SO questions/tags scenario however am trying to decide the best way of implementation. Tables Questions, QuestionTags and Tags Questions QuestionTags Tags --------- ------------ ---- QID QID TID QName TID TName When adding/updating a question I have 2 textboxes. The important part is a single textbox that allows users to enter in multiple Tags separated by spaces. I am using Linq2Sql so the Questions model has an EntitySet of QuestionTags with then link to Tags. My question is regarding the adding/updating of Questions (part 1), and also how to best show QuestionTags for a Question (part 2). Part 1 Before performing an add/update, my service layer needs to deal with 3 scenarios before passing to their respective repositories. Insert Tags that do not already exist Insert/Update Question Insert QuestionTags - when updating need to remove existing QuestionTags Here is my code below however started to get into a bit of a muddle. I've created extension methods on my repositories to get Tags WithNames etc. public void Add(Question q, string tags) { var tagList = tags.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries).ToList(); using (DB.TransactionScope ts = new DB.TransactionScope()) { var existingTags = TagsRepository.Get() .WithName(tagList) .ToList(); var newTags = (from t in tagList select new Tag { TName = t }).Except(existingTags, new TagsComparer()).ToList(); TagsRepository.Add(newTags); //need to insert QuestionTags QuestionsRepository.Add(q); ts.Complete(); } } Part 2 My second question is, when displaying a list of Questions how is it best to show their QuestionTags? For example, I have an Index view that shows a list of Questions in a table. One of the columns shows an image and when the user hovers over it shows the list of Tags. My current implementation is to create a custom ViewModel and show a List of QuestionIndexViewModel in the View. QuestionIndexViewModel { Question Question { get; set; } string Tags { get; set; } } However, this seems a bit clumsy and quite a few DB calls. public ViewResult Index() { var model= new List<QuestionIndexViewModel>(); //make a call to get a list of questions //foreach question make a call to get their QuestionTags, //to be able to get their Tag names and then join them //to form a single string. return View(model); } Also, just for test purposes using SQL Profiler, I decided to iterate through the QuestionTags entity set of a Question in my ViewModel however nothing was picked up in Profiler? What would be the reason for this?

    Read the article

  • LINQ Except operator and object equality

    - by Abhijeet Patel
    Here is an interesting issue I noticed when using the Except Operator: I have list of users from which I want to exclude some users: The list of users is coming from an XML file: The code goes like this: interface IUser { int ID { get; set; } string Name { get; set; } } class User: IUser { #region IUser Members public int ID { get; set; } public string Name { get; set; } #endregion public override string ToString() { return ID + ":" +Name; } public static IEnumerable<IUser> GetMatchingUsers(IEnumerable<IUser> users) { IEnumerable<IUser> localList = new List<User> { new User{ ID=4, Name="James"}, new User{ ID=5, Name="Tom"} }.OfType<IUser>(); var matches = from u in users join lu in localList on u.ID equals lu.ID select u; return matches; } } class Program { static void Main(string[] args) { XDocument doc = XDocument.Load("Users.xml"); IEnumerable<IUser> users = doc.Element("Users").Elements("User").Select (u => new User { ID = (int)u.Attribute("id"), Name = (string)u.Attribute("name") } ).OfType<IUser>(); //still a query, objects have not been materialized var matches = User.GetMatchingUsers(users); var excludes = users.Except(matches); // excludes should contain 6 users but here it contains 8 users } } When I call User.GetMatchingUsers(users) I get 2 matches as expected. The issue is that when I call users.Except(matches) The matching users are not being excluded at all! I am expecting 6 users ut "excludes" contains all 8 users instead. Since all I'm doing in GetMatchingUsers(IEnumerable users) is taking the IEnumerable and just returning the IUsers whose ID's match( 2 IUsers in this case), my understanding is that by default "Except" will use reference equality for comparing the objects to be excluded. Is this not how "Except" behaves? What is even more interesting is that if I materialize the objects using .ToList() and then get the matching users, and call "Except", everything works as expected! Like so: IEnumerable users = doc.Element("Users").Elements("User").Select (u = new User { ID = (int)u.Attribute("id"), Name = (string)u.Attribute("name") } ).OfType().ToList(); //explicity materializing all objects by calling ToList() var matches = User.GetMatchingUsers(users); var excludes = users.Except(matches); // excludes now contains 6 users as expected I don't see why I should need to materialize objects for calling "Except" given that its defined on IEnumerable? Any suggesstions / insights would be much appreciated.

    Read the article

  • LINQ2SQL: how to merge two columns from the same table into a single list

    - by TomL
    this is probably a simple question, but I'm only a beginner so... Suppose I have a table containing home-work locations (cities) certain people use. Something like: ID(int), namePerson(string), homeLocation(string), workLocation(string) where homeLocation and workLocation can both be null. Now I want all the different locations that are used merged into a single list. Something like: var homeLocation = from hm in Places where hm.Home != null select hm.Home; var workLocation = from wk in Places where wk.Work != null select wk.Work; List<string> locationList = new List<string>(); locationList = homeLocation.Distinct().ToList<string>(); locationList.AddRange(workLocation.Distinct().ToList<string>()); (which I guess would still allow duplicates if they have the same value in both columns, which I don't really want...) My question: how this be put into a single LINQ statement? Thanks in advance for your help!

    Read the article

  • Lambda expressions and nullable types

    - by Mathew
    I have two samples of code. One works and returns the correct result, one throws a null reference exception. What's the difference? I know there's some magic happening with capturing variables for the lambda expression but I don't understand what's going on behind the scenes here. int? x = null; bool isXNull = !x.HasValue; // this works var result = from p in data.Program where (isXNull) select p; return result.Tolist(); // this doesn't var result2 = from p in data.Program where (!x.HasValue) select p; return result2.ToList();

    Read the article

  • Can C# make my class look like another class?

    - by Vaccano
    I have a class that look like this: public class BasePadWI { public WorkItem WorkItemReference { get; set; } .... Other stuff ...... } I then have a dictionary that is defined like this: public Dictionary<BasePadWI, Canvas> Pad { get; set; } I would then like to make a call like this: List<WorkItem> workItems = Pad.Keys.ToList(); (Note: WorkItem is a sealed class, so I cannot inherit.) Is there some trickery that I could do in the class to make it look like a WorkItem? I have done this in the mean time: List<WorkItem> workItems = Pad.Keys.ToList().ConvertAll(x=>x.WorkItem);

    Read the article

  • How to limit select items with L2E/S?

    - by orlon
    This code is a no-go var errors = (from error in db.ELMAH_Error select new { error.Application, error.Host, error.Type, error.Source, error.Message, error.User, error.StatusCode, error.TimeUtc }).ToList(); return View(errors); as it results in a 'requires a model of type IEnumerable' error. The following code of course works fine, but selects all the columns, some of which I'm simply not interested in: var errors = (from error in db.ELMAH_Error select error).ToList(); return View(errors); I'm brand spanking new to MVC2 + L2E, so maybe I'm just not thinking in the right mindset yet, but this seems counter-intuitive. Is there an easy way to select a limited number of columns, or is this just part of using an ORM?

    Read the article

  • Adding a Categorylist to all pages with MVC4

    - by Sidriel
    I'm new with MVC4 and just MVC. I have a homecontroller and a categorycontroller. The categorycontroller sends data from the model to the categoryIndex view. That's works fine. But now I want to add the categorylist on all the available controllers. I already fixed this to add in all classes return view(db.categorys.ToList()); and add categoryIndex to the shared folder. In _layout.cshtml I'm adding a@RenderPage("~/")` and this works. But when I have to pass more than only the (db.categorys.ToList()) in the return it goes wrong. How can I fixed this problem. How do I add the categorylist too every controller and page properly?

    Read the article

  • How to save checkbox checked values in Database

    - by user1298215
    How to save checkbox values in database. Below is my view code. @foreach (var item in Model) { @Html.CheckBox("statecheck", (IEnumerable<SelectListItem>)ViewData["StatesList"]) @Html.DisplayFor(modelItem => item.state_name) </br> } <input class="ASPbutton" type="submit" value="submit"/> Below is My controller. public ActionResult States() { ViewData["StatesList"] = new SelectList(am.FindUpcomingStates().ToList(), "state_id", "state_Name"); return View(); } My model is public IQueryable<state> FindUpcomingStates() { return from state in Adm.states orderby state.state_name select state; } After clicking submit button checked item state_id will be saved into database. I wrote like below in Controller, but i got true or false values, i want state_id [AcceptVerbs(HttpVerbs.Post)] public ActionResult States(string _stateName, char[] statecheck, FormCollection formvalues) { statecheck = Request.Form["statecheck"].ToArray(); ViewData["StatesList"] = new SelectList(am.FindUpcomingStates222().ToList(), "state_id", "state_id", _stateName); }

    Read the article

  • Can the below function be improve?(C#3.0)

    - by Newbie
    I have the below function public static List<DateTime> GetOnlyFridays(DateTime endDate, int weeks, bool isIncludeBaseDate) { //Get only the fridays from the date range List<DateTime> dtlist = new List<DateTime>(); List<DateTime> tempDtlist = (from dtFridays in GetDates(endDate, weeks) where dtFridays.DayOfWeek == DayOfWeek.Friday select dtFridays).ToList(); if (isIncludeBaseDate) { dtlist = tempDtlist.Skip(1).ToList(); dtlist.Add(endDate); } else { dtlist = tempDtlist; } return dtlist; } What basically I am doing is getting the datelist using the GetDates function and then depending on the isIncludeBaseDate bool value(if true) skipping the last date and adding the Base Date It is working fine but can this program can be improve? I am using C#3.0 and Framework 3.5 Thanks

    Read the article

  • Filter condition not working properly on list (C#3.0)

    - by Newbie
    I have a datatable that has many NULL or " " strings. Next I am type casting the DataTable to a list . Now if I want to filter those conditions on this list and get the resultant value(without NULL or String.Empty or " " records) what should I do? My code DataTableExtensions.AsEnumerable(dt).ToList().ForEach(i => { if (i[0] != null) { if ((i[0].ToString() != string.Empty)|| (i[0].ToString() != " ")) { list = dt.AsEnumerable().ToList(); } } }); But I am getting all the records. It is not getting filtered. Using C#3.0 Please help Thanks

    Read the article

  • Mapping over multiple Seq in Scala

    - by bsdfish
    Suppose I have val foo : Seq[Double] = ... val bar : Seq[Double] = ... and I wish to produce a seq where the baz(i) = foo(i) + bar(i). One way I can think of to do this is val baz : Seq[Double] = (foo.toList zip bar.toList) map ((f: Double, b : Double) => f+b) However, this feels both ugly and inefficient -- I have to convert both seqs to lists (which explodes with lazy lists), create this temporary list of tuples, only to map over it and let it be GCed. Maybe streams solve the lazy problem, but in any case, this feels like unnecessarily ugly. In lisp, the map function would map over multiple sequences. I would write (mapcar (lambda (f b) (+ f b)) foo bar) And no temporary lists would get created anywhere. Is there a map-over-multiple-lists function in Scala, or is zip combined with destructuring really the 'right' way to do this?

    Read the article

  • How to look for different types of files in a directory?

    - by herrow
    public List<string> MapMyFiles() { List<FileInfo> batchaddresses = new List<FileInfo>(); foreach (object o in lstViewAddresses.Items) { try { string[] files = Directory.GetFiles(o.ToString(), "*-E.esy"); files.ToList().ForEach(f => batchaddresses.Add(new FileInfo(f))); } catch { if(MessageBox.Show(o.ToString() + " does not exist. Process anyway?", "Continue?", MessageBoxButtons.YesNo) == DialogResult.Yes) { } else { Application.Exit(); } } } return batchaddresses.OrderBy(f => f.CreationTime) .Select(f => f.FullName).ToList(); } i would like to add to the array not only .ESY but also "p-.csv" how do i do this?

    Read the article

  • Intersection() and Except() is too slow with large collections of custom objects

    - by Theo
    I am importing data from another database. My process is importing data from a remote DB into a List<DataModel> named remoteData and also importing data from the local DB into a List<DataModel> named localData. I am then using LINQ to create a list of records that are different so that I can update the local DB to match the data pulled from remote DB. Like this: var outdatedData = this.localData.Intersect(this.remoteData, new OutdatedDataComparer()).ToList(); I am then using LINQ to create a list of records that no longer exist in remoteData, but do exist in localData, so that I delete them from local database. Like this: var oldData = this.localData.Except(this.remoteData, new MatchingDataComparer()).ToList(); I am then using LINQ to do the opposite of the above to add the new data to the local database. Like this: var newData = this.remoteData.Except(this.localData, new MatchingDataComparer()).ToList(); Each collection imports about 70k records, and each of the 3 LINQ operation take between 5 - 10 minutes to complete. How can I make this faster? Here is the object the collections are using: internal class DataModel { public string Key1{ get; set; } public string Key2{ get; set; } public string Value1{ get; set; } public string Value2{ get; set; } public byte? Value3{ get; set; } } The comparer used to check for outdated records: class OutdatedDataComparer : IEqualityComparer<DataModel> { public bool Equals(DataModel x, DataModel y) { var e = string.Equals(x.Key1, y.Key1) && string.Equals(x.Key2, y.Key2) && ( !string.Equals(x.Value1, y.Value1) || !string.Equals(x.Value2, y.Value2) || x.Value3 != y.Value3 ); return e; } public int GetHashCode(DataModel obj) { return 0; } } The comparer used to find old and new records: internal class MatchingDataComparer : IEqualityComparer<DataModel> { public bool Equals(DataModel x, DataModel y) { return string.Equals(x.Key1, y.Key1) && string.Equals(x.Key2, y.Key2); } public int GetHashCode(DataModel obj) { return 0; } }

    Read the article

  • How Can I Get a List<int> From Linq to XML that Produces List<List<int>>?

    - by DaveDev
    I have an XML snippet as follows: <PerformancePanel> <LegalText> <Line id="300" /> <Line id="304" /> <Line id="278" /> </LegalText> </PerformancePanel> I'm using the following code to get an object: var performancePanels = new { Panels = (from panel in doc.Elements("PerformancePanel") select new { LegalTextIds = (from legalText in panel.Elements("LegalText").Elements("Line") select new List<int>() { (int)legalText.Attribute("id") }).ToList() }).ToList() }; The type of LegalTextIds is List<List<int>>. How can I get this as a List<int>?

    Read the article

  • Soapi.CS : A fully relational fluent .NET Stack Exchange API client library

    - by Sky Sanders
    Soapi.CS for .Net / Silverlight / Windows Phone 7 / Mono as easy as breathing...: var context = new ApiContext(apiKey).Initialize(false); Question thisPost = context.Official .StackApps .Questions.ById(386) .WithComments(true) .First(); Console.WriteLine(thisPost.Title); thisPost .Owner .Questions .PageSize(5) .Sort(PostSort.Votes) .ToList() .ForEach(q=> { Console.WriteLine("\t" + q.Score + "\t" + q.Title); q.Timeline.ToList().ForEach(t=> Console.WriteLine("\t\t" + t.TimelineType + "\t" + t.Owner.DisplayName)); Console.WriteLine(); }); // if you can think it, you can get it. Output Soapi.CS : A fully relational fluent .NET Stack Exchange API client library 21 Soapi.CS : A fully relational fluent .NET Stack Exchange API client library Revision code poet Revision code poet Votes code poet Votes code poet Revision code poet Revision code poet Revision code poet Votes code poet Votes code poet Votes code poet Revision code poet Revision code poet Revision code poet Revision code poet Revision code poet Revision code poet Revision code poet Revision code poet Revision code poet Revision code poet Votes code poet Comment code poet Revision code poet Votes code poet Revision code poet Revision code poet Revision code poet Answer code poet Revision code poet Revision code poet 14 SOAPI-WATCH: A realtime service that notifies subscribers via twitter when the API changes in any way. Votes code poet Revision code poet Votes code poet Comment code poet Comment code poet Comment code poet Votes lfoust Votes code poet Comment code poet Comment code poet Comment code poet Comment code poet Revision code poet Comment lfoust Votes code poet Revision code poet Votes code poet Votes lfoust Votes code poet Revision code poet Comment Dave DeLong Revision code poet Revision code poet Votes code poet Comment lfoust Comment Dave DeLong Comment lfoust Comment lfoust Comment Dave DeLong Revision code poet 11 SOAPI-EXPLORE: Self-updating single page JavaSript API test harness Votes code poet Votes code poet Votes code poet Votes code poet Votes code poet Comment code poet Revision code poet Votes code poet Revision code poet Revision code poet Revision code poet Comment code poet Revision code poet Votes code poet Comment code poet Question code poet Votes code poet 11 Soapi.JS V1.0: fluent JavaScript wrapper for the StackOverflow API Comment George Edison Comment George Edison Comment George Edison Comment George Edison Comment George Edison Comment George Edison Answer George Edison Votes code poet Votes code poet Votes code poet Votes code poet Revision code poet Revision code poet Answer code poet Comment code poet Revision code poet Comment code poet Comment code poet Comment code poet Revision code poet Revision code poet Votes code poet Votes code poet Votes code poet Votes code poet Comment code poet Comment code poet Comment code poet Comment code poet Comment code poet 9 SOAPI-DIFF: Your app broke? Check SOAPI-DIFF to find out what changed in the API Votes code poet Revision code poet Comment Dennis Williamson Answer Dennis Williamson Votes code poet Votes Dennis Williamson Comment code poet Question code poet Votes code poet About A robust, fully relational, easy to use, strongly typed, end-to-end StackOverflow API Client Library. Out of the box, Soapi provides you with a robust client library that abstracts away most all of the messy details of consuming the API and lets you concentrate on implementing your ideas. A few features include: A fully relational model of the API data set exposed via a fully 'dot navigable' IEnumerable (LINQ) implementation. Simply tell Soapi what you want and it will get it for you. e.g. "On my first question, from the author of the first comment, get the first page of comments by that person on any post" my.Questions.First().Comments.First().Owner.Comments.ToList(); (yes this is a real expression that returns the data as expressed!) Full coverage of the API, all routes and all parameters with an intuitive syntax. Strongly typed Domain Data Objects for all API data structures. Eager and Lazy Loading of 'stub' objects. Eager\Lazy loading may be disabled. When finer grained control of requests is desired, the core RouteMap objects may be leveraged to request data from any of the API paths using all available parameters as documented on the help pages. A rich Asynchronous implementation. A configurable request cache to reduce unnecessary network traffic and to simplify your usage logic. There is no need to go out of your way to be frugal. You may set a distinct cache duration for any particular route. A configurable request throttle to ensure compliance with the api terms of usage and to simplify your code in that you do not have to worry about and respond to 50X errors. The RequestCache and Throttled Queue are thread-safe, so can make as many requests as you like from as many threads as you like as fast as you like and not worry about abusing the api or having to write reams of management/compensation code. Configurable retry threshold that will, by default, make up to 3 attempts to retrieve a request before failing. Every request made by Soapi is properly formed and directed so most any http error will be the result of a timeout or other network infrastructure. A retry buffer provides a level of fault tolerance that you can rely on. An almost identical javascript library, Soapi.JS, and it's full figured big brother, Soapi.JS2, that will enable you to leverage your server cycles and bandwidth for only those tasks that require it and offload things like status updates to the client's browser. License Licensed GPL Version 2 license. Why is Soapi.CS GPL? Can I get an LGPL license for Soapi.CS? (hint: probably) Platforms .NET 3.5 .NET 4.0 Silverlight 3 Silverlight 4 Windows Phone 7 Mono Download Source code lives @ http://soapics.codeplex.com. Binary releases are forthcoming. codeplex is acting up again. get the source and binaries @ http://bitbucket.org/bitpusher/soapi.cs/downloads The source is C# 3.5. and includes projects and solutions for the following IDEs Visual Studio 2008 Visual Studio 2010 ModoDevelop 2.4 Documentation Full documentation is available at http://soapi.info/help/cs/index.aspx Sample Code / Usage Examples Sample code and usage examples will be added as answers to this question. Full API Coverage all API routes are covered Full Parameter Parity If the API exposes it, Soapi giftwraps it for you. Building a simple app with Soapi.CS - a simple app that gathers all traces of a user in the whole stackiverse. Fluent Configuration - Setting up a Soapi.ApiContext could not be easier Bulk Data Import - A tiny app that quickly loads a SQLite data file with all users in the stackiverse. Paged Results - Soapi.CS transparently handles multi-page operations. Asynchronous Requests - Soapi.CS provides a rich asynchronous model that is especially useful when writing api apps in Silverlight or Windows Phone 7. Caching and Throttling - how and why Apps that use Soapi.CS Soapi.FindUser - .net utility for locating a user anywhere in the stackiverse Soapi.Explore - The entire API at your command Soapi.LastSeen - List users by last access time Add your app/site here - I know you are out there ;-) if you are not comfortable editing this post, simply add a comment and I will add it. The CS/SL/WP7/MONO libraries all compile the same code and with the exception of environmental considerations of Silverlight, the code samples are valid for all libraries. You may also find guidance in the test suites. More information on the SOAPI eco-system. Contact This library is currently the effort of me, Sky Sanders (code poet) and can be reached at gmail - sky.sanders Any who are interested in improving this library are welcome. Support Soapi You can help support this project by voting for Soapi's Open Source Ad post For more information about the origins of Soapi.CS and the rest of the Soapi eco-system see What is Soapi and why should I care?

    Read the article

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