Search Results

Search found 2563 results on 103 pages for 'collections'.

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

  • Initial review of Developer's Guide to Collections in Microsoft® .NET

    - by TATWORTH
    The code is well illustrated by diagrams. The approach is practical. The code is well commented, however the C# code samples would be better had they been fully Style Cop compliant. I am looking forward to reviewing the rest of this excellent book. I recommend this book to all C# and VB.NET Development teams. I concur with the author who states that the book is not for learning C# or VB.NET. It is an excellent book for C# or VB.NET developers to extend their knowledge of the Dot Net framework. To buy a copy, please go to http://shop.oreilly.com/product/0790145317193.do

    Read the article

  • Observable Collections

    - by SGWellens
    I didn't think it was possible, but .NET surprised me yet again with a cool feature I never knew existed: The ObservableCollection. This became available in .NET 3.0. In essence, an ObservableCollection is a collection with an event you can connect to. The event fires when the collection changes. As usual, working with the .NET classes is so ridiculously easy, it feels like cheating. The following is small test program to illustrate how the ObservableCollection works. To start, create an ObservableCollection and then store it in the Session object so it will persist between page post backs. I also added the code to pull it out of Session state when there is a page post back:   public partial class _Default : System.Web.UI.Page{    public ObservableCollection<int> MyInts;     // ---- Page_Load ------------------------------     protected void Page_Load(object sender, EventArgs e)    {        if (IsPostBack == false)        {            MyInts = new ObservableCollection<int>();            MyInts.CollectionChanged += CollectionChangedHandler;             Session["MyInts"] = MyInts;  // store for use between postbacks        }        else        {            MyInts = Session["MyInts"] as ObservableCollection<int>;        }    } Here's the event handler I hooked up to the ObservableCollection, it writes status strings to a ListBox. Note: The event handler fires in a different thread than the IIS process thread.     // ---- CollectionChangedHandler -----------------------------------    //    // Something changed in the Observable collection     public void CollectionChangedHandler(object sender, NotifyCollectionChangedEventArgs e)    {        // need to dig around to get the current page and control to write to:        // (because this is in a separate thread)        Page CurrentPage = System.Web.HttpContext.Current.Handler as Page;        ListBox LB = CurrentPage.FindControl("ListBoxHistory") as ListBox;         switch (e.Action)        {            case NotifyCollectionChangedAction.Add:                LB.Items.Add("Add: " + e.NewItems[0]);                               break;             case NotifyCollectionChangedAction.Remove:                LB.Items.Add("Remove: " + e.OldItems[0]);                break;             case NotifyCollectionChangedAction.Reset:                LB.Items.Add("Reset: ");                break;             default:                LB.Items.Add(e.Action.ToString());                break;                     }    }  Next, add some buttons and code to exercise the ObservableCollection:     <br />    <asp:Button ID="ButtonAdd" runat="server" Text="Add" OnClick="ButtonAdd_Click" />    <asp:Button ID="ButtonRemove" runat="server" Text="Remove" OnClick="ButtonRemove_Click" />    <asp:Button ID="ButtonReset" runat="server" Text="Reset" OnClick="ButtonReset_Click" />    <asp:Button ID="ButtonList" runat="server" Text="List" OnClick="ButtonList_Click" />    <br />    <asp:TextBox ID="TextBoxInt" runat="server" Width="51px"></asp:TextBox>    <br />    <asp:ListBox ID="ListBoxHistory" runat="server" Height="255px" Width="195px">    </asp:ListBox>    // ---- Add Button --------------------------------------     protected void ButtonAdd_Click(object sender, EventArgs e)    {        int Temp;        if (int.TryParse(TextBoxInt.Text, out Temp) == true)            MyInts.Add(Temp);    }     // ---- Remove Button --------------------------------------     protected void ButtonRemove_Click(object sender, EventArgs e)    {        int Temp;        if (int.TryParse(TextBoxInt.Text, out Temp) == true)            MyInts.Remove(Temp);    }     // ---- Button Reset -----------------------------------     protected void ButtonReset_Click(object sender, EventArgs e)    {        MyInts.Clear();    }     // ---- Button List --------------------------------------     protected void ButtonList_Click(object sender, EventArgs e)    {        ListBoxHistory.Items.Add("MyInts:");        foreach (int i in MyInts)        {            // a bit of tweaking to get the text to be indented            ListItem LI = new ListItem("&nbsp;&nbsp;" + i.ToString());            LI.Text = Server.HtmlDecode(LI.Text);            ListBoxHistory.Items.Add(LI);        }    } Here's what it looks like after entering some numbers and clicking some buttons: An interesting note is that I had to use: System.Web.HttpContext.Current.Response to write to a control on the page. As mentioned earlier, this implies that the notification event is in a thread separate from the IIS thread. Another interesting note: From the online help: Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe What does that mean to Asp.Net developers? If you are going to share an ObservableCollection among different sessions, you'd better make it a static object. I hope someone finds this useful. Steve Wellens

    Read the article

  • Object model design: collections on classes

    - by Luke Puplett
    Hi all, Consider Train.Passengers, what type would you use for Passengers where passengers are not supposed to be added or removed by the consuming code? I'm using .NET Framework, so this discussion would suit .NET, but it could apply to a number of modern languages/frameworks. In the .NET Framework, the List is not supposed to be publicly exposed. There's Collection and ICollection and guidance, which I tend to agree with, is to return the closest concrete type down the inheritance tree, so that'd be Collection since it is already an ICollection. But Collection has read/write semantics and so possibly it should be a ReadOnlyCollection, but its arguably common sense not to alter the contents of a collection that you don't have intimate knowledge about so is it necessary? And it requires extra work internally and can be a pain with (de)serialization. At the extreme ends I could just return Person[] (since LINQ now provides much of the benefits that previously would have been afforded by a more specified collection) or even build a strongly-typed PersonCollection or ReadOnlyPersonCollection! What do you do? Thanks for your time. Luke

    Read the article

  • Les Collections en Objective-C : Manipuler les tableaux, introduction à NSArray et NSMutableArray par Sylvain Gamel

    Retrouvez un nouvel article d'introduction aux tableaux d'objets : NSArray et à NSMutableArray. Citation: Les tableaux d'objets sont une structure de données courante et très souvent utilisées. Qu'est-ce qu'un tableau ? Un tableau est une liste ordonnée d'objets où chaque objet peut être accédé par sa position dans le tableau : son index. Java et Cocoa proposent évidemment des classes pour mettre en oeuvre ces structures de données. Cet article se propose d'introduire rapidement les principales fonctionnalités offe...

    Read the article

  • Silverlight Binding with multiple collections

    - by George Evjen
    We're designing some sport specific applications. In one of our views we have a gridview that is bound to an observable collection of Teams. This is pretty straight forward in terms of getting Teams bound to the GridView. <telerik:RadGridView Grid.Row="0" Grid.Column="0" x:Name="UsersGrid" ItemsSource="{Binding TeamResults}" SelectedItem="{Binding SelectedTeam, Mode=TwoWay}"> <telerik:RadGridView.Columns> <telerik:GridViewDataColumn Header="Name/Group" DataMemberBinding="{Binding TeamName}" MinWidth="150"></telerik:GridViewDataColumn> </telerik:RadGridView.Columns> </telerik:RadGridView> We use the observable collection of teams as our items source and then bind the property of TeamName to the first column. You can set the binding to mode=TwoWay, we use a dialog where we edit the selected item, so our binding here is not set to two way. The issue comes when we want to bind to a property that has another collection in it. To continue on our code from above, we have an observable collection of teams, within that collection we have a collection of KeyPeople. We get this collection using RIA Serivces with the code below. return _TeamsRepository.All().Include("KeyPerson"); Here we are getting all the teams and also including the KeyPerson entity. So when we are done with our Load we will end up with an observable collection of Teams with a navigation property / entity of KeyPerson. Within this KeyPerson entity is a list of people associated with that particular team. We want to display the head coach from this list of KeyPersons. This list currently has a list of ten or more people that are bound to this team, but we just want to display the Head Coach in the column next to team name. The issue becomes how do we bind to this included entity? I have found about three different ways to solve this issue. The way that seemed to fit us best is to utilize the features within RIA Services. We can create client side properties that will do the work for us. We will create in the client side library a partial class of Team. We will end up in our library a file that is Team.shared.cs. The code below is what we will put into our partial team class. public KeyPerson Coach        {            get            {                if (this.KeyPerson != null && this.KeyPerson.Any())                { return this.KeyPerson.Where(x => x.RelationshipType == “HeadCoach”).FirstOrDefault(); }                 return null;            }        } We will return just the person that is the Head Coach and then be able to bind that and any other additional properties that we need. <telerik:GridViewDataColumn Header="Coach" DataMemberBinding="{Binding Coach.Name}" MinWidth="150"></telerik:GridViewDataColumn> There are other ways that we could have solved this issue but we felt that creating a partial class through RIA Services best suited our needs.

    Read the article

  • Getting data from csv file and returning objects in collections

    - by Jacob
    I have very simple class of person as below: public class Person { int ID; Gender gender; Date dateOfBirth; public Person(final int iD, final Gender gender,final Date dateOfBirth) { ID = iD; this.gender = gender; this.dateOfBirth = dateOfBirth; } } Gender is enum : public enum Gender { Male, Female } In CSV file i will have data, for example: 1;Male;23-02-2001 2;Female;11-06-1989 3;Male;02-12-1999 Is in java any simple way to get all persons from csv file and return it as ArrayList<Person> persons ?

    Read the article

  • GamingUnity Organizes Your Game Collections

    - by Jason Fitzpatrick
    If you’re having trouble keeping track of your game collection GamingUnity will help you get things on organizational lock down–add games from any console, view them with a nice bookshelf interface, and quickly sort them. Sign up for a free account, start searching, and click “Add to collection” until you’ve worked your way through your games. In addition to just cataloging your existing games you can mark games as completed or add future games to your wish list. Hit up the link below to browse the archives and sign up for a free account. GamingUnity Can Dust Actually Damage My Computer? What To Do If You Get a Virus on Your Computer Why Enabling “Do Not Track” Doesn’t Stop You From Being Tracked

    Read the article

  • Hibernate HQL and Grails- How do I compare collections?

    - by BurtP
    Hi everyone (my first post!), I have an HQL question (in Groovy/Grails) I was hoping someone could help me with. I have a simple Asset object with a one-to-many Tags collection. class Asset { Set tags static hasMany = [tags:Tag] } class Tag { String name } What I'm trying to do in HQL: A user passes in some tags in params.tags (ex: groovy grails rocks) and wants to return Asset(s) that have those tags, and only those exact tags. Here's my HQL that returns Assets if one or more of the tags are present in an Assets tags: SELECT DISTINCT a FROM Asset a LEFT JOIN a.tags t WHERE t IN (:tags) assetList = Asset.executeQuery( hql, [tags:tokenizedTagListFromParams] The above code works perfect, but its really like an OR. If any of the tag(s) are found, it will return that Asset. I only want to return Assets that have those exact same tags (in number as well). Every time a new tag is created, I new Tag(name:xxx).save() so I can get the Tag instances and unique ID's for each tag that was asked for. I also tried converting the passed in tags to a list of Tag instances with Tag.findByName(t1) for each tag, and also a list of (unique) Tag Id's into the HQL above with no luck. I would appreciate any help/advice. Thank you for your time, Burt

    Read the article

  • Two collections and a for loop. (Urgent help needed) Checking an object variable against an inputted

    - by Elliott
    Hi there, I'm relatively new to java, I'm certain the error is trivial. But can't for the life of me spot it. I have an end of term exam on monday and currently trying to get to grips with past papers! Anyway heregoes, in another method (ALGO_1) I search over elements of and check the value H_NAME equals a value entered in the main. When I attempt to run the code I get a null pointer exception, also upon trying to print (with System.out.println etc) the H_NAME value after each for loop in the snippet I also get a null statement returned to me. I am fairly certain that the collection is simply not storing the data gathered up by the Scanner. But then again when I check the collection size with size() it is about the right size. Either way I'm pretty lost and would appreciate the help. Main questions I guess to ask are: from the readBackground method is the data.add in the wrong place? is the snippet simply structured wrongly? oh and another point when I use System.out.println to check the Background object values name, starttime, increment etc they print out fine. Thanks in advance.(PS im guessing the formatting is terrible, apologies.) snippet of code: for(Hydro hd: hydros){ System.out.println(hd.H_NAME); for(Background back : backgs){ System.out.println(back.H_NAME); if(back.H_NAME.equals(hydroName)){ //get error here public static Collection<Background> readBackground(String url) throws IOException { URL u = new URL(url); InputStream is = u.openStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader b = new BufferedReader(isr); String line =""; Vector<Background> data = new Vector<Background>(); while((line = b.readLine())!= null){ Scanner s = new Scanner(line); String name = s.next(); double starttime = Double.parseDouble(s.next()); double increment = Double.parseDouble(s.next()); double sum = 0; double p = 0; double nterms = 0; while((s.hasNextDouble())){ p = Double.parseDouble(s.next()); nterms++; sum += p; } double pbmean = sum/nterms; Background SAMP = new Background(name, starttime, increment, pbmean); data.add(SAMP); } return data; } Edit/Delete Message

    Read the article

  • What is the answer to this homework about maps and collections? [closed]

    - by Bishan
    Maps collection is referred to an dictionary because of the way it works. Each entry into a maps collection involves a pair of objects. In a maps collection, an object associates the key which determines where the object is stored in the map. The key object in the maps collection can be duplicated. A stack which has Last In First Out storage mechanism can be considered as a maps collection. I think #1,#2,#3 and #5 are Correct in above, but I have doubt with #5. Am I correct?

    Read the article

  • Unmodifiable NavigableSet/NavigableMap in Java?

    - by Greg Mattes
    java.util.Collections has several unmodifiable methods that provide unmodifiable collection views by wrapping collections in decorators that prohibit mutation operations. Java 6 added support for java.util.NavigableSet and java.util.NavigableMap. I'd like to be able to have unmodifiable NavigableSets and NavigableMaps, but java.util.Collections#unmodifiableSortedSet(SortedSet) and java.util.Collections#unmodifiableSortedMap(SortedMap) are not sufficient because they do not support the operations that are particular to NavigableSet and NavigableMap. Are there de-facto implementations for unmodifiableNavigableSet and unmodifiableNavigableMap?

    Read the article

  • Is Collections.shuffle suitable for a poker algorithm?

    - by Kovu
    Hi, there is a poker-system in java, that uses Collections.shuffle() on all available cards before the cards are dealt. So a collection of 52 cards 2-9, J, Q, K, A in 4 types. After that we Collections.shuffle(). The problem is, that it seems (until now we didn't have big statistic, it's possible that we only see a lot of statistic inferences), that the algorithm is VERY unclearly. So, is Collections.shuffle() okay for a poker algorithm?

    Read the article

  • Bi-directional view model syncing with "live" collections and properties (MVVM)

    - by Schneider
    I am getting my knickers in a twist recently about View Models (VM). Just like this guy I have come to the conclusion that the collections I need to expose on my VM typically contain a different type to the collections exposed on my business objects. Hence there must be a bi-directional mapping or transformation between these two types. (Just to complicate things, on my project this data is "Live" such that as soon as you change a property it gets transmitted to other computers) I can just about cope with that concept, using a framework like Truss, although I suspect there will be a nasty surprise somewhere within. Not only must objects be transformed but a synchronization between these two collections is required. (Just to complicate things I can think of cases where the VM collection might be a subset or union of business object collections, not simply a 1:1 synchronization). I can see how to do a one-way "live" sync, using a replicating ObservableCollection or something like CLINQ. The problem then becomes: What is the best way to create/delete items? Bi-directinal sync does not seem to be on the cards - I have found no such examples, and the only class that supports anything remotely like that is the ListCollectionView. Would bi-directional sync even be a sensible way to add back into the business object collection? All the samples I have seen never seem to tackle anything this "complex". So my question is: How do you solve this? Is there some technique to update the model collections from the VM? What is the best general approach to this?

    Read the article

  • Collections in C#

    - by Oghenero
    am converting a vb.net component to c#, i get this error Using the generic type 'System.Collections.ObjectModel.Collection<T>' requires '1' type arguments This is what i did in VB.NET i had this Private _bufferCol As Collection i did this in c# private Collection _bufferCol = new Collection(); My declaration is using Microsoft.VisualBasi; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Collections.ObjectModel; Can any body help me please.

    Read the article

  • The best way to assign an immutable instance to a Collection in Java

    - by Ali
    Today I was reading through some Hibernate code and I encounter something interesting. There is a class called CollectionHelper that defines the following constant varibale: public final class CollectionHelper { public static final List EMPTY_LIST = Collections.unmodifiableList( new ArrayList(0 ) ; public static final Collection EMPTY_COLLECTION = Collections.unmodifiableCollection(new ArrayList(0) ); public static final Map EMPTY_MAP = Collections.unmodifiableMap( new HashMap(0) ); They have used these constants to initialize collections with immutable instances. Why they didn't simply use the Collections.EMPTY_LIST for initializing lists? Is there a benefit in using the following method?

    Read the article

  • Multiple collections tied to one base collection with filters and eventing

    - by damienc88
    I have a complex model served from my back end, which has a bunch of regular attributes, some nested models, and a couple of collections. My page has two tables, one for invalid items, and one for valid items. The items in question are from one of the nested collections. Let's call it baseModel.documentCollection, implementing DocumentsCollection. I don't want any filtration code in my Marionette.CompositeViews, so what I've done is the following (note, duplicated for the 'valid' case): var invalidDocsCollection = new DocumentsCollection( baseModel.documentCollection.filter(function(item) { return !item.isValidItem(); }) ); var invalidTableView = new BookIn.PendingBookInRequestItemsCollectionView({ collection: app.collections.invalidDocsCollection }); layout.invalidDocsRegion.show(invalidTableView); This is fine for actually populating two tables independently, from one base collection. But I'm not getting the whole event pipeline down to the base collection, obviously. This means when a document's validity is changed, there's no neat way of it shifting to the other collection, therefore the other view. What I'm after is a nice way of having a base collection that I can have filter collections sit on top of. Any suggestions?

    Read the article

  • Shallow Copy vs DeepCopy in C#.NET

    Hope below example helps to understand the difference. Please drop a comment if any doubts. using System; using System.IO; using System.Runtime.Serialization.Formatters.Binary; namespace ShallowCopyVsDeepCopy {     class Program     {         static void Main(string[] args)         {             var e1 = new Emp { EmpNo = 10, EmpName = "Smith", Department = new Dep { DeptNo = 100, DeptName = "Finance" } };             var e2 = e1.ShallowClone();             e1.Department.DeptName = "Accounts";             Console.WriteLine(e2.Department.DeptName);             var e3 = new Emp { EmpNo = 10, EmpName = "Smith", Department = new Dep { DeptNo = 100, DeptName = "Finance" } };             var e4 = e3.DeepClone();             e3.Department.DeptName = "Accounts";             Console.WriteLine(e4.Department.DeptName);         }     }     [Serializable]     class Dep     {         public int DeptNo { get; set; }         public String DeptName { get; set; }     }     [Serializable]     class Emp     {         public int EmpNo { get; set; }         public String EmpName { get; set; }         public Dep Department { get; set; }         public Emp ShallowClone()         {             return (Emp)this.MemberwiseClone();         }         public Emp DeepClone()         {             MemoryStream ms = new MemoryStream();             BinaryFormatter bf = new BinaryFormatter();             bf.Serialize(ms, this);             ms.Seek(0, SeekOrigin.Begin);             object copy = bf.Deserialize(ms);             ms.Close();             return copy as Emp;         }     } } span.fullpost {display:none;}

    Read the article

  • Is throwing an error in unpredictable subclass-specific circumstances a violation of LSP?

    - by Motti Strom
    Say, I wanted to create a Java List<String> (see spec) implementation that uses a complex subsystem, such as a database or file system, for its store so that it becomes a simple persistent collection rather than an basic in-memory one. (We're limiting it specifically to a List of Strings for the purposes of discussion, but it could extended to automatically de-/serialise any object, with some help. We can also provide persistent Sets, Maps and so on in this way too.) So here's a skeleton implementation: class DbBackedList implements List<String> { private DbBackedList() {} /** Returns a list, possibly non-empty */ public static getList() { return new DbBackedList(); } public String get(int index) { return Db.getTable().getRow(i).asString(); // may throw DbExceptions! } // add(String), add(int, String), etc. ... } My problem lies with the fact that the underlying DB API may encounter connection errors that are not specified in the List interface that it should throw. My problem is whether this violates Liskov's Substitution Principle (LSP). Bob Martin actually gives an example of a PersistentSet in his paper on LSP that violates LSP. The difference is that his newly-specified Exception there is determined by the inserted value and so is strengthening the precondition. In my case the connection/read error is unpredictable and due to external factors and so is not technically a new precondition, merely an error of circumstance, perhaps like OutOfMemoryError which can occur even when unspecified. In normal circumstances, the new Error/Exception might never be thrown. (The caller could catch if it is aware of the possibility, just as a memory-restricted Java program might specifically catch OOME.) Is this therefore a valid argument for throwing an extra error and can I still claim to be a valid java.util.List (or pick your SDK/language/collection in general) and not in violation of LSP? If this does indeed violate LSP and thus not practically usable, I have provided two less-palatable alternative solutions as answers that you can comment on, see below. Footnote: Use Cases In the simplest case, the goal is to provide a familiar interface for cases when (say) a database is just being used as a persistent list, and allow regular List operations such as search, subList and iteration. Another, more adventurous, use-case is as a slot-in replacement for libraries that work with basic Lists, e.g if we have a third-party task queue that usually works with a plain List: new TaskWorkQueue(new ArrayList<String>()).start() which is susceptible to losing all it's queue in event of a crash, if we just replace this with: new TaskWorkQueue(new DbBackedList()).start() we get a instant persistence and the ability to share the tasks amongst more than one machine. In either case, we could either handle connection/read exceptions that are thrown, perhaps retrying the connection/read first, or allow them to throw and crash the program (e.g. if we can't change the TaskWorkQueue code).

    Read the article

  • Shallow Copy vs DeepCopy in C#.NET

    Hope below example helps to understand the difference. Please drop a comment if any doubts. using System; using System.IO; using System.Runtime.Serialization.Formatters.Binary; namespace ShallowCopyVsDeepCopy {     class Program     {         static void Main(string[] args)         {             var e1 = new Emp { EmpNo = 10, EmpName = "Smith", Department = new Dep { DeptNo = 100, DeptName = "Finance" } };             var e2 = e1.ShallowClone();             e1.Department.DeptName = "Accounts";             Console.WriteLine(e2.Department.DeptName);             var e3 = new Emp { EmpNo = 10, EmpName = "Smith", Department = new Dep { DeptNo = 100, DeptName = "Finance" } };             var e4 = e3.DeepClone();             e3.Department.DeptName = "Accounts";             Console.WriteLine(e4.Department.DeptName);         }     }     [Serializable]     class Dep     {         public int DeptNo { get; set; }         public String DeptName { get; set; }     }     [Serializable]     class Emp     {         public int EmpNo { get; set; }         public String EmpName { get; set; }         public Dep Department { get; set; }         public Emp ShallowClone()         {             return (Emp)this.MemberwiseClone();         }         public Emp DeepClone()         {             MemoryStream ms = new MemoryStream();             BinaryFormatter bf = new BinaryFormatter();             bf.Serialize(ms, this);             ms.Seek(0, SeekOrigin.Begin);             object copy = bf.Deserialize(ms);             ms.Close();             return copy as Emp;         }     } } span.fullpost {display:none;}

    Read the article

  • How can a collection class instantiate many objects with one database call?

    - by Buttle Butkus
    I have a baseClass where I do not want public setters. I have a load($id) method that will retrieve the data for that object from the db. I have been using static class methods like getBy($property,$values) to return multiple class objects using a single database call. But some people say that static methods are not OOP. So now I'm trying to create a baseClassCollection that can do the same thing. But it can't, because it cannot access protected setters. I don't want everyone to be able to set the object's data. But it seems that it is an all-or-nothing proposition. I cannot give just the collection class access to the setters. I've seen a solution using debug_backtrace() but that seems inelegant. I'm moving toward just making the setters public. Are there any other solutions? Or should I even be looking for other solutions?

    Read the article

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