Search Results

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

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

  • Issue converting Sitecore Item[] using ToList<T>

    - by philba888
    Working with Sitecore and Linq extensions. I am trying to convert to from an item array to the list using the following piece of code: Item variationsFolder = masterDB.SelectSingleItem(VariationsFolderID.ToString()); List<Item> variationList = variationsFolder.GetChildren().ToList<Item>(); However I keep getting this error whenever I try to build: 'Sitecore.Collections.ChildList' does not contain a definition for 'ToList' and the best extension method overload 'System.Linq.Enumerable.ToList<TSource>(System.Collections.Generic.IEnumerable<TSource>)' has some invalid arguments I have the following usings: using System.Linq; using System.Xml.Linq; Am referencing: System.Core I've just copied this code from another location, so it should work fine, can only think that there is something simple (like a reference or something that I am missing).

    Read the article

  • ToList()-- Does it Create a New List?

    - by Ngu Soon Hui
    Let's say I have a class public class MyObject { public int SimpleInt{get;set;} } And I have a List<MyObject>, and I ToList() it and then change one of the SimpleInt, will my change be propagated back to the original list. In other words, what would be the output of the following method? public void RunChangeList() { var objs = new List<MyObject>(){new MyObject(){SimpleInt=0}}; var whatInt = ChangeToList(objs ); } public int ChangeToList(List<MyObject> objects) { var objectList = objects.ToList(); objectList[0].SimpleInt=5; return objects[0].SimpleInt; } Why? P/S: I'm sorry if it seems obvious to find out. But I don't have compiler with me now...

    Read the article

  • stack.ToList() in .NET - order of elements?

    - by James M.
    When using the .ToList() extension method on a Stack<T>, is the result the same as popping each element and adding to a new list (reverse of what was pushed)? If so, is this because it really is iterating over each element, or does it store the elements in reverse internally and slip the array into a new List<T>?

    Read the article

  • Compile error when calling ToList() when accessing many to many with Linq To Entities

    - by KallDrexx
    I can't figure out what I am doing wrong. I have the following method: public IList<WObject> GetRelationshipMembers(int relId) { var members = from r in _container.ObjectRelationships where r.Id == relId select r.WObjects; return members.ToList<WObject>(); } This returns the following error: Instance argument: cannot convert from 'System.Linq.IQueryable<System.Data.Objects.DataClasses.EntityCollection<Project.DomainModel.Entities.WObject>>' to 'System.Collections.Generic.IEnumerable<Project.DomainModel.Entities.WObject>' How can I convert the EntityCollection to a list without lazy loading?

    Read the article

  • Using ComplexType with ToList causes InvalidOperationException

    - by Chris Paynter
    I have this model namespace ProjectTimer.Models { public class TimerContext : DbContext { public TimerContext() : base("DefaultConnection") { } public DbSet<Project> Projects { get; set; } public DbSet<ProjectTimeSpan> TimeSpans { get; set; } } public class DomainBase { [Key] public int Id { get; set; } } public class Project : DomainBase { public UserProfile User { get; set; } public string Name { get; set; } public string Description { get; set; } public IList<ProjectTimeSpan> TimeSpans { get; set; } } [ComplexType] public class ProjectTimeSpan { public DateTime TimeStart { get; set; } public DateTime TimeEnd { get; set; } public bool Active { get; set; } } } When I try to use this action I get the exception The type 'ProjectTimer.Models.ProjectTimeSpan' has already been configured as an entity type. It cannot be reconfigured as a complex type. public ActionResult Index() { using (var db = new TimerContext()) { return View(db.Projects.ToList); } } The view is using the model @model IList<ProjectTimer.Models.Project> Can any one shine some light as to why this would be happening?

    Read the article

  • SelectMany in Linq to entity

    - by Brazeta
    I was looking at some examples in microsoft site about linq and I see an example that I need to modify! http://msdn.microsoft.com/en-us/vcsharp/aa336758.aspx#SelectManyCompoundfrom3 public void Linq16() { List customers = GetCustomerList(); var orders = from c in customers from o in c.Orders where o.OrderDate >= new DateTime(1998, 1, 1) select new { c.CustomerID, o.OrderID, o.OrderDate }; ObjectDumper.Write(orders); } Insted of having a select that retrives the CustomerID, OrderID and OrderDate I want to select the CustomerID and a System.Collection.Generic.List that contains all the orders for that user! Essentially I want to group my orders by CustomerID, but i noticed that linq to entity does not allow a .ToList(object) inside the select. I want something like this... List customers = GetCustomerList(); var orders = from c in customers from o in c.Orders where o.OrderDate >= new DateTime(1998, 1, 1) select new xpto { TheCostumerID = c.CustomerID, CostumerOrders = o.Select(i=>i.OrderID).ToList(), }; ...but the .ToList() is a big problem, at least for me. I'm trying to find out the solution for that but so far I have acomplished nothing! Please help me.

    Read the article

  • Convert to list after Cast<T>

    - by Timmie Sarjanen
    Hi, I need to convert an IQueryable to List(is it possible to convert to IList?). There had not been an problem if it was not that i need to Cast because I have interfaces to my objects. I've tried most things but for some reason I must run Cast first and then ToList() which generates System.NullReferenceException. How do I solve this? public IQueryable GetPhrases() { return (from r in _repository.All<Phrase>() select r).Cast<IPhrase() }

    Read the article

  • LINQtoSQL: Query to return List<String>

    - by ctrlShiftBryan
    I have a LINQ query that returns some object like this... var query = from c in db.Customers where ... select c; Then I do this List<String> list = new List<String>(); foreach (ProgramLanguage c in query) { //GetUL returns a String list.Add(GetUL(c.Property,c.Property2)); } Is there a way to combine into something list this? var query = from c in db.Customers where ... select new { GetUL(c.Property,c.Property2) }).ToList<String>();

    Read the article

  • why datetime.now not work when I didn't use tolist?

    - by MemoryLeak
    When I use datacontext.News .Where(p => p.status == true) .Where(p => p.date <= DateTime.Now) .ToList(); the system will return no results; When I use datacontext.News .Where(p => p.status == true) .ToList() .Where(p => p.date <= DateTime.Now) .ToList(); system will return expected results. Can anyone tell me what's up? Thanks in advance !

    Read the article

  • Where is the best place to call the .tolist(); inside my controller classes or inside my model repository classes

    - by john G
    I have the following action method, inside my asp.net mvc web application:- public JsonResult LoadZoneByDataCenter(string id) { var zonelist = repository.getrealtedzone(Convert.ToInt32(id)).ToList(); //code goes here Which calls the following model repository method:- public IQueryable<Zone> getrealtedzone(int? dcid) { return tms.Zones.Where(a=> a.DataCenterID == dcid || dcid == null); } Currently I am calling the .tolist() which will interpret the Database from my action method, but my question is where is the best place to call the .tolist() inside the controller or inside the model classes and why ? thanks

    Read the article

  • Rhino Mocks, AssertWasCalled with Arg Constraint on array parameter

    - by Etienne Giust
    Today, I had a hard time unit testing a function to make sure a Method with some array parameters was called. Method to be called : void AddUsersToRoles(string[] usernames, string[] roleNames);   I had previously used Arg<T>.Matches on complex types in other unit tests, but for some reason I was unable to find out how to apply the same logic with an array of strings.   It is actually quite simple to do, T really is a string[], so we use Arg<string[]>. As for the Matching part, a ToList() allows us to leverage the lambda expression.   sut.PermissionServices.AssertWasCalled(                 l => l.AddUsersToRoles(                     Arg<string[]>.Matches(a => a.ToList().First() == UserId.ToString())                     ,Arg<string[]>.Matches(a => a.ToList().First() == expectedRole1 && a.ToList()[1] == expectedRole2)                     )                     );   Of course, iw we expect an array with 2 or more values, the math would be something like : a => a.ToList()[0] == value1 && a.ToList()[1] == value2    … etc.

    Read the article

  • C#/.NET &ndash; Finding an Item&rsquo;s Index in IEnumerable&lt;T&gt;

    - by James Michael Hare
    Sorry for the long blogging hiatus.  First it was, of course, the holidays hustle and bustle, then my brother and his wife gave birth to their son, so I’ve been away from my blogging for two weeks. Background: Finding an item’s index in List<T> is easy… Many times in our day to day programming activities, we want to find the index of an item in a collection.  Now, if we have a List<T> and we’re looking for the item itself this is trivial: 1: // assume have a list of ints: 2: var list = new List<int> { 1, 13, 42, 64, 121, 77, 5, 99, 132 }; 3:  4: // can find the exact item using IndexOf() 5: var pos = list.IndexOf(64); This will return the position of the item if it’s found, or –1 if not.  It’s easy to see how this works for primitive types where equality is well defined.  For complex types, however, it will attempt to compare them using EqualityComparer<T>.Default which, in a nutshell, relies on the object’s Equals() method. So what if we want to search for a condition instead of equality?  That’s also easy in a List<T> with the FindIndex() method: 1: // assume have a list of ints: 2: var list = new List<int> { 1, 13, 42, 64, 121, 77, 5, 99, 132 }; 3:  4: // finds index of first even number or -1 if not found. 5: var pos = list.FindIndex(i => i % 2 == 0);   Problem: Finding an item’s index in IEnumerable<T> is not so easy... This is all well and good for lists, but what if we want to do the same thing for IEnumerable<T>?  A collection of IEnumerable<T> has no indexing, so there’s no direct method to find an item’s index.  LINQ, as powerful as it is, gives us many tools to get us this information, but not in one step.  As with almost any problem involving collections, there are several ways to accomplish the same goal.  And once again as with almost any problem involving collections, the choice of the solution somewhat depends on the situation. So let’s look at a few possible alternatives.  I’m going to express each of these as extension methods for simplicity and consistency. Solution: The TakeWhile() and Count() combo One of the things you can do is to perform a TakeWhile() on the list as long as your find condition is not true, and then do a Count() of the items it took.  The only downside to this method is that if the item is not in the list, the index will be the full Count() of items, and not –1.  So if you don’t know the size of the list beforehand, this can be confusing. 1: // a collection of extra extension methods off IEnumerable<T> 2: public static class EnumerableExtensions 3: { 4: // Finds an item in the collection, similar to List<T>.FindIndex() 5: public static int FindIndex<T>(this IEnumerable<T> list, Predicate<T> finder) 6: { 7: // note if item not found, result is length and not -1! 8: return list.TakeWhile(i => !finder(i)).Count(); 9: } 10: } Personally, I don’t like switching the paradigm of not found away from –1, so this is one of my least favorites.  Solution: Select with index Many people don’t realize that there is an alternative form of the LINQ Select() method that will provide you an index of the item being selected: 1: list.Select( (item,index) => do something here with the item and/or index... ) This can come in handy, but must be treated with care.  This is because the index provided is only as pertains to the result of previous operations (if any).  For example: 1: // assume have a list of ints: 2: var list = new List<int> { 1, 13, 42, 64, 121, 77, 5, 99, 132 }; 3:  4: // you'd hope this would give you the indexes of the even numbers 5: // which would be 2, 3, 8, but in reality it gives you 0, 1, 2 6: list.Where(item => item % 2 == 0).Select((item,index) => index); The reason the example gives you the collection { 0, 1, 2 } is because the where clause passes over any items that are odd, and therefore only the even items are given to the select and only they are given indexes. Conversely, we can’t select the index and then test the item in a Where() clause, because then the Where() clause would be operating on the index and not the item! So, what we have to do is to select the item and index and put them together in an anonymous type.  It looks ugly, but it works: 1: // extensions defined on IEnumerable<T> 2: public static class EnumerableExtensions 3: { 4: // finds an item in a collection, similar to List<T>.FindIndex() 5: public static int FindIndex<T>(this IEnumerable<T> list, Predicate<T> finder) 6: { 7: // if you don't name the anonymous properties they are the variable names 8: return list.Select((item, index) => new { item, index }) 9: .Where(p => finder(p.item)) 10: .Select(p => p.index + 1) 11: .FirstOrDefault() - 1; 12: } 13: }     So let’s look at this, because i know it’s convoluted: First Select() joins the items and their indexes into an anonymous type. Where() filters that list to only the ones matching the predicate. Second Select() picks the index of the matches and adds 1 – this is to distinguish between not found and first item. FirstOrDefault() returns the first item found from the previous clauses or default (zero) if not found. Subtract one so that not found (zero) will be –1, and first item (one) will be zero. The bad thing is, this is ugly as hell and creates anonymous objects for each item tested until it finds the match.  This concerns me a bit but we’ll defer judgment until compare the relative performances below. Solution: Convert ToList() and use FindIndex() This solution is easy enough.  We know any IEnumerable<T> can be converted to List<T> using the LINQ extension method ToList(), so we can easily convert the collection to a list and then just use the FindIndex() method baked into List<T>. 1: // a collection of extension methods for IEnumerable<T> 2: public static class EnumerableExtensions 3: { 4: // find the index of an item in the collection similar to List<T>.FindIndex() 5: public static int FindIndex<T>(this IEnumerable<T> list, Predicate<T> finder) 6: { 7: return list.ToList().FindIndex(finder); 8: } 9: } This solution is simplicity itself!  It is very concise and elegant and you need not worry about anyone misinterpreting what it’s trying to do (as opposed to the more convoluted LINQ methods above). But the main thing I’m concerned about here is the performance hit to allocate the List<T> in the ToList() call, but once again we’ll explore that in a second. Solution: Roll your own FindIndex() for IEnumerable<T> Of course, you can always roll your own FindIndex() method for IEnumerable<T>.  It would be a very simple for loop which scans for the item and counts as it goes.  There’s many ways to do this, but one such way might look like: 1: // extension methods for IEnumerable<T> 2: public static class EnumerableExtensions 3: { 4: // Finds an item matching a predicate in the enumeration, much like List<T>.FindIndex() 5: public static int FindIndex<T>(this IEnumerable<T> list, Predicate<T> finder) 6: { 7: int index = 0; 8: foreach (var item in list) 9: { 10: if (finder(item)) 11: { 12: return index; 13: } 14:  15: index++; 16: } 17:  18: return -1; 19: } 20: } Well, it’s not quite simplicity, and those less familiar with LINQ may prefer it since it doesn’t include all of the lambdas and behind the scenes iterators that come with deferred execution.  But does having this long, blown out method really gain us much in performance? Comparison of Proposed Solutions So we’ve now seen four solutions, let’s analyze their collective performance.  I took each of the four methods described above and run them over 100,000 iterations of lists of size 10, 100, 1000, and 10000 and here’s the performance results.  Then I looked for targets at the begining of the list (best case), middle of the list (the average case) and not in the list (worst case as must scan all of the list). Each of the times below is the average time in milliseconds for one execution as computer over the 100,000 iterations: Searches Matching First Item (Best Case)   10 100 1000 10000 TakeWhile 0.0003 0.0003 0.0003 0.0003 Select 0.0005 0.0005 0.0005 0.0005 ToList 0.0002 0.0003 0.0013 0.0121 Manual 0.0001 0.0001 0.0001 0.0001   Searches Matching Middle Item (Average Case)   10 100 1000 10000 TakeWhile 0.0004 0.0020 0.0191 0.1889 Select 0.0008 0.0042 0.0387 0.3802 ToList 0.0002 0.0007 0.0057 0.0562 Manual 0.0002 0.0013 0.0129 0.1255   Searches Where Not Found (Worst Case)   10 100 1000 10000 TakeWhile 0.0006 0.0039 0.0381 0.3770 Select 0.0012 0.0081 0.0758 0.7583 ToList 0.0002 0.0012 0.0100 0.0996 Manual 0.0003 0.0026 0.0253 0.2514   Notice something interesting here, you’d think the “roll your own” loop would be the most efficient, but it only wins when the item is first (or very close to it) regardless of list size.  In almost all other cases though and in particular the average case and worst case, the ToList()/FindIndex() combo wins for performance, even though it is creating some temporary memory to hold the List<T>.  If you examine the algorithm, the reason why is most likely because once it’s in a ToList() form, internally FindIndex() scans the internal array which is much more efficient to iterate over.  Thus, it takes a one time performance hit (not including any GC impact) to create the List<T> but after that the performance is much better. Summary If you’re concerned about too many throw-away objects, you can always roll your own FindIndex() method, but for sheer simplicity and overall performance, using the ToList()/FindIndex() combo performs best on nearly all list sizes in the average and worst cases.    Technorati Tags: C#,.NET,Litte Wonders,BlackRabbitCoder,Software,LINQ,List

    Read the article

  • How to combine the multiple part linq into one query?

    - by user2943399
    Operator should be ‘AND’ and not a ‘OR’. I am trying to refactor the following code and i understood the following way of writing linq query may not be the correct way. Can somone advice me how to combine the following into one query. AllCompany.Where(itm => itm != null).Distinct().ToList(); if (AllCompany.Count > 0) { //COMPANY NAME if (isfldCompanyName) { AllCompany = AllCompany.Where(company => company["Company Name"].StartsWith(fldCompanyName)).ToList(); } //SECTOR if (isfldSector) { AllCompany = AllCompany.Where(company => fldSector.Intersect(company["Sectors"].Split('|')).Any()).ToList(); } //LOCATION if (isfldLocation) { AllCompany = AllCompany.Where(company => fldLocation.Intersect(company["Location"].Split('|')).Any()).ToList(); } //CREATED DATE if (isfldcreatedDate) { AllCompany = AllCompany.Where(company => company.Statistics.Created >= createdDate).ToList(); } //LAST UPDATED DATE if (isfldUpdatedDate) { AllCompany = AllCompany.Where(company => company.Statistics.Updated >= updatedDate).ToList(); } //Allow Placements if (isfldEmployerLevel) { fldEmployerLevel = (fldEmployerLevel == "Yes") ? "1" : ""; AllCompany = AllCompany.Where(company => company["Allow Placements"].ToString() == fldEmployerLevel).ToList(); }

    Read the article

  • Help in debugging the string concatenation code

    - by mithun1538
    I have a code to concatenate strings. However, for some reason, the final string is not a combination of the required strings. Consider the following code : //cusEmail is of type String[] String toList = ""; for(i=0; i < cusEmail.length - 1; i++) { toList.concat(cusEmail[i]); toList.concat("; "); System.out.println(cusEmail[i]); } toList.concat(cusEmail[i]); System.out.println(toList); The first sout statement displays the strings in cusEmail[i] correctly. However, once concatenated, the second sout displays a blank / empty. Any reason for this? Am i concatenating it correctly?

    Read the article

  • Linq2Sql: query - subquery optimisation

    - by Budda
    I have the following query: IList<InfrStadium> stadiums = (from sector in DbContext.sectors where sector.Type=typeValue select new InfrStadium(sector.TeamId) ).ToList(); and InfrStadium class constructor: private InfrStadium(int teamId) { IList<Sector> teamSectors = (from sector in DbContext.sectors where sector.TeamId==teamId select sector) .ToList<>(); ... work with data } Current implementation perform 1+n queries, where n - number of records fetched the 1st time. I want to optimize that. And another one I would love to do using 'group' operator in way like this: IList<InfrStadium> stadiums = (from sector in DbContext.sectors group sector by sector.TeamId into team_sectors select new InfrStadium(team_sectors.Key, team_sectors) ).ToList(); with appropriate constructor: private InfrStadium(int iTeamId, IEnumerable<InfrStadiumSector> eSectors) { IList<Sector> teamSectors = eSectors.ToList(); ... work with data } But attempt to launch query causes the following error: Expression of type 'System.Int32' cannot be used for constructor parameter of type 'System.Collections.Generic.IEnumerable`1[InfrStadiumSector]' Question 1: Could you please explain, what is wrong here, I don't understand why 'team_sectors' is applied as 'System.Int32'? I've tried to change query a little (replace IEnumerable with IQueryeable): IList<InfrStadium> stadiums = (from sector in DbContext.sectors group sector by sector.TeamId into team_sectors select new InfrStadium(team_sectors.Key, team_sectors.AsQueryable()) ).ToList(); with appropriate constructor: private InfrStadium(int iTeamId, IQueryeable<InfrStadiumSector> eSectors) { IList<Sector> teamSectors = eSectors.ToList(); ... work with data } In this case I've received another but similar error: Expression of type 'System.Int32' cannot be used for parameter of type 'System.Collections.Generic.IEnumerable1[InfrStadiumSector]' of method 'System.Linq.IQueryable1[InfrStadiumSector] AsQueryableInfrStadiumSector' Question 2: Actually, the same question: can't understand at all what is going on here... P.S. I have another to optimize query idea (describe here: Linq2Sql: query optimisation) but I would love to find a solution with 1 request to DB).

    Read the article

  • List querying with Lamda Expressions in C#.NET

    - by Pavan Kumar Pabothu
    public class Employees {     public int EmployeeId { get; set; }     public string Name { get; set; }     public decimal Salary { get; set; } } List<Employees> employeeList = new List<Employees>(); List<Employees> resultList = new List<Employees>(); decimal maxSalary; List<string> employeeNames = new List<string>(); protected void Page_Load(object sender, EventArgs e) {     if (!IsPostBack)     {         FillEmployees();     }     // Getting a max salary     maxSalary = employeeList.Max((emp) => emp.Salary);     // Filtering a List     resultList = employeeList.Where((emp) => emp.Salary > 50000).ToList();     // Sorting a List     // To get a descending order replace OrderBy with OrderByDescending     resultList = employeeList.OrderBy<Employees, decimal>((emp) => emp.Salary).ToList();     // Get the List of employee names only     employeeNames = employeeList.Select<Employees, string>(emp => emp.Name).ToList();        // Getting a customized object with a given list     var employeeResultSet = employeeList.Select((emp) => new { Name = emp.Name, BigSalary = emp.Salary > 50000 }).ToList(); } private void FillEmployees() {     employeeList.Add(new Employees { EmployeeId = 1, Name = "Shankar", Salary = 125000 });     employeeList.Add(new Employees { EmployeeId = 2, Name = "Prasad", Salary = 90000 });     employeeList.Add(new Employees { EmployeeId = 3, Name = "Mahesh", Salary = 36000 }); }

    Read the article

  • List<T> and IEnumerable difference

    - by Jonas Elfström
    While implementing this generic merge sort, as a kind of Code Kata, I stumbled on a difference between IEnumerable and List that I need help to figure out. Here's the MergeSort public class MergeSort<T> { public IEnumerable<T> Sort(IEnumerable<T> arr) { if (arr.Count() <= 1) return arr; int middle = arr.Count() / 2; var left = arr.Take(middle).ToList(); var right = arr.Skip(middle).ToList(); return Merge(Sort(left), Sort(right)); } private static IEnumerable<T> Merge(IEnumerable<T> left, IEnumerable<T> right) { var arrSorted = new List<T>(); while (left.Count() > 0 && right.Count() > 0) { if (Comparer<T>.Default.Compare(left.First(), right.First()) < 0) { arrSorted.Add(left.First()); left=left.Skip(1); } else { arrSorted.Add(right.First()); right=right.Skip(1); } } return arrSorted.Concat(left).Concat(right); } } If I remove the .ToList() on the left and right variables it fails to sort correctly. Do you see why? Example var ints = new List<int> { 5, 8, 2, 1, 7 }; var mergeSortInt = new MergeSort<int>(); var sortedInts = mergeSortInt.Sort(ints); With .ToList() [0]: 1 [1]: 2 [2]: 5 [3]: 7 [4]: 8 Without .ToList() [0]: 1 [1]: 2 [2]: 5 [3]: 7 [4]: 2 Edit It was my stupid test that got me. I tested it like this: var sortedInts = mergeSortInt.Sort(ints); ints.Sort(); if (Enumerable.SequenceEqual(ints, sortedInts)) Console.WriteLine("ints sorts ok"); just changing the first row to var sortedInts = mergeSortInt.Sort(ints).ToList(); removes the problem (and the lazy evaluation). EDIT 2010-12-29 I thought I would figure out just how the lazy evaluation messes things up here but I just don't get it. Remove the .ToList() in the Sort method above like this var left = arr.Take(middle); var right = arr.Skip(middle); then try this var ints = new List<int> { 5, 8, 2 }; var mergeSortInt = new MergeSort<int>(); var sortedInts = mergeSortInt.Sort(ints); ints.Sort(); if (Enumerable.SequenceEqual(ints, sortedInts)) Console.WriteLine("ints sorts ok"); When debugging You can see that before ints.Sort() a sortedInts.ToList() returns [0]: 2 [1]: 5 [2]: 8 but after ints.Sort() it returns [0]: 2 [1]: 5 [2]: 5 What is really happening here?

    Read the article

  • System.AccessViolationException when using TPT inheritance in Entity Framework CTP5

    - by Ben
    Hi, I'm using TPT inheritance in EF CTP5 with SQL CE 4. I have an abstract base class "Widget" with common properties like "Title". I can successfully save concrete Widget implementations e.g. "TwitterWidget". However, I have a problem retrieving all widgets (or rather ALL widget implementations). My repository exposes the following: public IQueryable<Widget> GetAll(); This effectively returns the IDbSet from the DbContext. The following queries work fine: repo.GetAll().ToList(); repo.GetAll().Where(w => w.Title == "Test").ToList(); repo.GetAll().SingleOrDefault(w => w.Title == "Test"); repo.GetAll().Where(w => w.Title == "Test").OrderBy(x => x.Title).ToList(); However, if I write the following query: repo.GetAll().OrderBy(w => w.Title); I get the following error: Test 'PlanetCloud.Portfolio.Tests.Data.PersistenceTestFixture.Can_get_widgets' failed: System.AccessViolationException : Attempted to read or write protected memory. This is often an indication that other memory is corrupt. at System.Data.SqlServerCe.NativeMethodsHelper.GetValues(IntPtr pSeCursor, Int32 seGetColumn, IntPtr prgBinding, Int32 cDbBinding, IntPtr pData, IntPtr pError) at System.Data.SqlServerCe.NativeMethods.GetValues(IntPtr pSeCursor, Int32 seGetColumn, IntPtr prgBinding, Int32 cDbBinding, IntPtr pData, IntPtr pError) at System.Data.SqlServerCe.SqlCeDataReader.FetchValue(Int32 index) at System.Data.SqlServerCe.SqlCeDataReader.IsDBNull(Int32 ordinal) at lambda_method(Closure , Shaper ) at System.Data.Common.Internal.Materialization.Shaper.HandleEntityAppendOnly[TEntity](Func`2 constructEntityDelegate, EntityKey entityKey, EntitySet entitySet) at lambda_method(Closure , Shaper ) at System.Data.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper) at System.Data.Common.Internal.Materialization.Shaper`1.SimpleEnumerator.MoveNext() at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source) However, I can execute the following query without problems: var widgets = repo.GetAll().OfType<Widget>().OrderBy(w => w.Title).ToList(); So if I specify the type as the base class prior to my orderby clause it works. The question is why?

    Read the article

  • C#/.NET Little Wonders: Use Cast() and TypeOf() to Change Sequence Type

    - by James Michael Hare
    Once again, in this series of posts I look at the parts of the .NET Framework that may seem trivial, but can help improve your code by making it easier to write and maintain. The index of all my past little wonders posts can be found here. We’ve seen how the Select() extension method lets you project a sequence from one type to a new type which is handy for getting just parts of items, or building new items.  But what happens when the items in the sequence are already the type you want, but the sequence itself is typed to an interface or super-type instead of the sub-type you need? For example, you may have a sequence of Rectangle stored in an IEnumerable<Shape> and want to consider it an IEnumerable<Rectangle> sequence instead.  Today we’ll look at two handy extension methods, Cast<TResult>() and OfType<TResult>() which help you with this task. Cast<TResult>() – Attempt to cast all items to type TResult So, the first thing we can do would be to attempt to create a sequence of TResult from every item in the source sequence.  Typically we’d do this if we had an IEnumerable<T> where we knew that every item was actually a TResult where TResult inherits/implements T. For example, assume the typical Shape example classes: 1: // abstract base class 2: public abstract class Shape { } 3:  4: // a basic rectangle 5: public class Rectangle : Shape 6: { 7: public int Widtgh { get; set; } 8: public int Height { get; set; } 9: } And let’s assume we have a sequence of Shape where every Shape is a Rectangle… 1: var shapes = new List<Shape> 2: { 3: new Rectangle { Width = 3, Height = 5 }, 4: new Rectangle { Width = 10, Height = 13 }, 5: // ... 6: }; To get the sequence of Shape as a sequence of Rectangle, of course, we could use a Select() clause, such as: 1: // select each Shape, cast it to Rectangle 2: var rectangles = shapes 3: .Select(s => (Rectangle)s) 4: .ToList(); But that’s a bit verbose, and fortunately there is already a facility built in and ready to use in the form of the Cast<TResult>() extension method: 1: // cast each item to Rectangle and store in a List<Rectangle> 2: var rectangles = shapes 3: .Cast<Rectangle>() 4: .ToList(); However, we should note that if anything in the list cannot be cast to a Rectangle, you will get an InvalidCastException thrown at runtime.  Thus, if our Shape sequence had a Circle in it, the call to Cast<Rectangle>() would have failed.  As such, you should only do this when you are reasonably sure of what the sequence actually contains (or are willing to handle an exception if you’re wrong). Another handy use of Cast<TResult>() is using it to convert an IEnumerable to an IEnumerable<T>.  If you look at the signature, you’ll see that the Cast<TResult>() extension method actually extends the older, object-based IEnumerable interface instead of the newer, generic IEnumerable<T>.  This is your gateway method for being able to use LINQ on older, non-generic sequences.  For example, consider the following: 1: // the older, non-generic collections are sequence of object 2: var shapes = new ArrayList 3: { 4: new Rectangle { Width = 3, Height = 13 }, 5: new Rectangle { Width = 10, Height = 20 }, 6: // ... 7: }; Since this is an older, object based collection, we cannot use the LINQ extension methods on it directly.  For example, if I wanted to query the Shape sequence for only those Rectangles whose Width is > 5, I can’t do this: 1: // compiler error, Where() operates on IEnumerable<T>, not IEnumerable 2: var bigRectangles = shapes.Where(r => r.Width > 5); However, I can use Cast<Rectangle>() to treat my ArrayList as an IEnumerable<Rectangle> and then do the query! 1: // ah, that’s better! 2: var bigRectangles = shapes.Cast<Rectangle>().Where(r => r.Width > 5); Or, if you prefer, in LINQ query expression syntax: 1: var bigRectangles = from s in shapes.Cast<Rectangle>() 2: where s.Width > 5 3: select s; One quick warning: Cast<TResult>() only attempts to cast, it won’t perform a cast conversion.  That is, consider this: 1: var intList = new List<int> { 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 }; 2:  3: // casting ints to longs, this should work, right? 4: var asLong = intList.Cast<long>().ToList(); Will the code above work?  No, you’ll get a InvalidCastException. Remember that Cast<TResult>() is an extension of IEnumerable, thus it is a sequence of object, which means that it will box every int as an object as it enumerates over it, and there is no cast conversion from object to long, and thus the cast fails.  In other words, a cast from int to long will succeed because there is a conversion from int to long.  But a cast from int to object to long will not, because you can only unbox an item by casting it to its exact type. For more information on why cast-converting boxed values doesn’t work, see this post on The Dangers of Casting Boxed Values (here). OfType<TResult>() – Filter sequence to only items of type TResult So, we’ve seen how we can use Cast<TResult>() to change the type of our sequence, when we expect all the items of the sequence to be of a specific type.  But what do we do when a sequence contains many different types, and we are only concerned with a subset of a given type? For example, what if a sequence of Shape contains Rectangle and Circle instances, and we just want to select all of the Rectangle instances?  Well, let’s say we had this sequence of Shape: 1: var shapes = new List<Shape> 2: { 3: new Rectangle { Width = 3, Height = 5 }, 4: new Rectangle { Width = 10, Height = 13 }, 5: new Circle { Radius = 10 }, 6: new Square { Side = 13 }, 7: // ... 8: }; Well, we could get the rectangles using Select(), like: 1: var onlyRectangles = shapes.Where(s => s is Rectangle).ToList(); But fortunately, an easier way has already been written for us in the form of the OfType<T>() extension method: 1: // returns only a sequence of the shapes that are Rectangles 2: var onlyRectangles = shapes.OfType<Rectangle>().ToList(); Now we have a sequence of only the Rectangles in the original sequence, we can also use this to chain other queries that depend on Rectangles, such as: 1: // select only Rectangles, then filter to only those more than 2: // 5 units wide... 3: var onlyBigRectangles = shapes.OfType<Rectangle>() 4: .Where(r => r.Width > 5) 5: .ToList(); The OfType<Rectangle>() will filter the sequence to only the items that are of type Rectangle (or a subclass of it), and that results in an IEnumerable<Rectangle>, we can then apply the other LINQ extension methods to query that list further. Just as Cast<TResult>() is an extension method on IEnumerable (and not IEnumerable<T>), the same is true for OfType<T>().  This means that you can use OfType<TResult>() on object-based collections as well. For example, given an ArrayList containing Shapes, as below: 1: // object-based collections are a sequence of object 2: var shapes = new ArrayList 3: { 4: new Rectangle { Width = 3, Height = 5 }, 5: new Rectangle { Width = 10, Height = 13 }, 6: new Circle { Radius = 10 }, 7: new Square { Side = 13 }, 8: // ... 9: }; We can use OfType<Rectangle> to filter the sequence to only Rectangle items (and subclasses), and then chain other LINQ expressions, since we will then be of type IEnumerable<Rectangle>: 1: // OfType() converts the sequence of object to a new sequence 2: // containing only Rectangle or sub-types of Rectangle. 3: var onlyBigRectangles = shapes.OfType<Rectangle>() 4: .Where(r => r.Width > 5) 5: .ToList(); Summary So now we’ve seen two different ways to get a sequence of a superclass or interface down to a more specific sequence of a subclass or implementation.  The Cast<TResult>() method casts every item in the source sequence to type TResult, and the OfType<TResult>() method selects only those items in the source sequence that are of type TResult. You can use these to downcast sequences, or adapt older types and sequences that only implement IEnumerable (such as DataTable, ArrayList, etc.). Technorati Tags: C#,CSharp,.NET,LINQ,Little Wonders,TypeOf,Cast,IEnumerable<T>

    Read the article

  • linq null refactoring code

    - by user276640
    i have code public List<Files> List(int? menuId) { if (menuId == null) { return _dataContext.Files.ToList(); } else { return _dataContext.Files.Where(f => f.Menu.MenuId == menuId).ToList(); } } is it possible to make it only one line like return _dataContext.Files.Where(f = f.Menu.MenuId == menuId).ToList();?

    Read the article

  • Why does one of these statements compile in Scala but not the other?

    - by Jeff
    (Note: I'm using Scala 2.7.7 here, not 2.8). I'm doing something pretty simple -- creating a map based on the values in a simple, 2-column CSV file -- and I've completed it easily enough, but I'm perplexed at why my first attempt didn't compile. Here's the code: // Returns Iterator[String] private def getLines = Source.fromFile(csvFilePath).getLines // This doesn't compile: def mapping: Map[String,String] = { Map(getLines map { line: String => val pairArr = line.split(",") pairArr(0) -> pairArr(1).trim() }.toList:_*) } // This DOES compile def mapping: Map[String,String] = { def strPair(line: String): (String,String) = { val pairArr = line.split(",") pairArr(0) -> pairArr(1).trim() } Map(getLines.map( strPair(_) ).toList:_*) } The compiler error is CsvReader.scala:16: error: value toList is not a member of (St ring) = (java.lang.String, java.lang.String) [scalac] possible cause: maybe a semicolon is missing before `value toList'? [scalac] }.toList:_*) [scalac] ^ [scalac] one error found So what gives? They seem like they should be equivalent to me, apart from the explicit function definition (vs. anonymous in the nonworking example) and () vs. {}. If I replace the curly braces with parentheses in the nonworking example, the error is "';' expected, but 'val' found." But if I remove the local variable definition and split the string twice AND use parens instead of curly braces, it compiles. Can someone explain this difference to me, preferably with a link to Scala docs explaining the difference between parens and curly braces when used to surround method arguments?

    Read the article

  • Create and populate two-dimensional array in Scala

    - by ~asteinlein
    What's the recommended way of creating a pre-populated two-dimensional array in Scala? I've got the following code: val map = for { x <- (1 to size).toList } yield for { y <- (1 to size).toList } yield (x, y) How do I make an array instead of list? Replacing .toList with .toArray doesn't compile. And is there a more concise or readable way of doing this than the nested for expressions?

    Read the article

  • Problem in converting ToDictionary<Datetime,double>() using LINQ(C#3.0)

    - by Newbie
    I have written the below return (from p in returnObject.Portfolios.ToList() from childData in p.ChildData.ToList() from retuns in p.Returns.ToList() select new Dictionary<DateTime, double> () { p.EndDate, retuns.Value } ).ToDictionary<DateTime,double>(); Getting error No overload for method 'Add' takes '1' arguments Where I am making the mistake I am using C#3.0 Thanks

    Read the article

  • Unable to type cast <AnonymousType#1> to <WindowsFormsApplication1.Attributes> [ C#3.0 ]

    - by Newbie
    I have List<Attributes> la = new List<Attributes>(); la = (from t in result let t1 = t.AttributeCollection from t2 in t1 where t2.AttributeCode.Equals(attributeType) let t3 = t2.TimeSeriesData from k in t3.ToList() where k.Key.Equals(startDate) && k.Key.Equals(endDate) select new { AttributeCode = attributeType, TimeSeriesData = fn(k.Key, k.Value.ToString()) }).ToList<Attributes>(); I am getting the error: 'System.Collections.Generic.IEnumerable<AnonymousType#1>' does not contain a definition for 'ToList' and the best extension method overload 'System.Linq.Enumerable.ToList<TSource>(System.Collections.Generic.IEnumerable<TSource>)' has some invalid arguments I understood tye error meaning but how to type cast it. I have used var and then iterating over it got the result. But without that any other way by which I can do it? Using C# 3.0 Thanks

    Read the article

  • Problem in converting ToDictionary<Datetime,double>() usinh LINQ(C#3.0)

    - by Newbie
    I have written the below return (from p in returnObject.Portfolios.ToList() from childData in p.ChildData.ToList() from retuns in p.Returns.ToList() select new Dictionary<DateTime, double> () {p.EndDate, retuns.Value }).ToDictionary<DateTime,double>(); Getting error No overload for method 'Add' takes '1' arguments Where I am making the mistake I am using C#3.0 Thanks

    Read the article

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