Search Results

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

Page 17/103 | < Previous Page | 13 14 15 16 17 18 19 20 21 22 23 24  | Next Page >

  • Ordered List of Keyvaluepairs?

    - by boris callens
    Is there an collection in .net that allows the storing KeyValuePair<string, string> that keeps the order of inserting? OrderedDictionary looked promising, but seems to be rather lacking. Now I'm looking into IOrderedEnumerable, but I can't seem to find any implementation except for ISortedDictionary, but that's not what I want. No sorting needs to be done, just the order of inserting is important.

    Read the article

  • Why doesn't java.util.Set have get(int index)?

    - by Marty Pitt
    I'm sure there's a good reason, but could someone please explain why the java.util.Set interface lacks get(int Index), or any similar get() method? It seems that sets are great for putting things into, but I can't find an elegant way of retrieving a single item from it. If I know I want the first item, I can use set.iterator().next(), but otherwise it seems I have to cast to an Array to retrieve an item at a specific index? What are the appropriate ways of retrieving data from a set? (other than using an iterator) I'm sure the fact that it's excluded from the API means there's a good reason for not doing this -- could someone please enlighten me? EDIT: Some extremely great answers here, and a few saying "more context". The specific scneario was a dbUnit test, where I could reasonalby assert that the returned set from a query had only 1 item, and I was trying to access that item. However, the question is more valid without the scenario, as it remains more focussed : What's the difference between set & list. Thanks to all for the fantastic answers below.

    Read the article

  • Java - Make an object collection friendly

    - by DutrowLLC
    If an object holds a unique primary key, what interfaces does it need to implement in order to be collection friendly especially in terms of being efficiently sortable, hashable, etc...? If the primary key is a string, how are these interfaces best implemented? Thanks!

    Read the article

  • Using 'or' in Java Generics declaration

    - by Shervin
    I have a method that returns an instance of Map<String, List<Foo>> x(); and another method that returns an instance of Map<String, Collection<Foo>> y(); Now if I want to dynamically add one of this Maps in my field, how can I write the generics for it to work? ie: public class Bar { private Map<String, ? extends Collection<Foo>> myMap; public void initializer() { if(notImportant) myMap = x(); //OK else myMap = y(); // !OK (Need cast to (Map<String, ? extends Collection<Foo>>) } Now is it ok that I cast to the signature even though the y() is declared as being Collection? } } If it is not ok to cast, can I somehow write this (Collection OR List) I mean, List is a Collection, so it should somehow be possible. private Map<String, Collection<Foo> | List<Foo>>> myMap;

    Read the article

  • Properly removing an Integer from a List<Integer>

    - by Yuval A
    Here's a nice pitfall I just encountered. Consider a list of integers: List<Integer> list = new ArrayList<Integer>(); list.add(5); list.add(6); list.add(7); list.add(1); Any educated guess on what happens when you execute list.remove(1)? What about list.remove(new Integer(1))? This can cause some nasty bugs. What is the proper way to differentiate between remove(int index), which removes an element from given index and remove(Object o), which removes an element by reference, when dealing with lists of integers? The main point to consider here is the one @Nikita mentioned - exact parameter matching takes precedence over auto-boxing.

    Read the article

  • C# Property Access vs Interface Implementation

    - by ehdv
    I'm writing a class to represent a Pivot Collection, the root object recognized by Pivot. A Collection has several attributes, a list of facet categories (each represented by a FacetCategory object) and a list of items (each represented by a PivotItem object). Therefore, an extremely simplified Collection reads: public class Collection { private List<FacetCategory> categories; private List<PivotItem> items; // other attributes } What I'm unsure of is how to properly grant access to those two lists. Because declaration order of both facet categories and items is visible to the user, I can't use sets, but the class also shouldn't allow duplicate categories or items. Furthermore, I'd like to make the Collection object as easy to use as possible. So my choices are: Have Collection implement IList<PivotItem> and have accessor methods for FacetCategory: In this case, one would add an item to Collection foo by writing foo.Add(bar). This works, but since a Collection is equally both kinds of list making it only pass as a list for one type (category or item) seems like a subpar solution. Create nested wrapper classes for List (CategoryList and ItemList). This has the advantage of making a consistent interface but the downside is that these properties would no longer be able to serve as lists (because I need to override the non-virtual Add method I have to implement IList rather than subclass List. Implicit casting wouldn't work because that would return the Add method to its normal behavior. Also, for reasons I can't figure out, IList is missing an AddRange method... public class Collection { private class CategoryList: IList<FacetCategory> { // ... } private readonly CategoryList categories = new CategoryList(); private readonly ItemList items = new ItemList(); public CategoryList FacetCategories { get { return categories; } set { categories.Clear(); categories.AddRange(value); } } public ItemList Items { get { return items; } set { items.Clear(); items.AddRange(value); } } } Finally, the third option is to combine options one and two, so that Collection implements IList<PivotItem> and has a property FacetCategories. Question: Which of these three is most appropriate, and why?

    Read the article

  • ResultSet and aggregation

    - by kachanov
    Ok, I admit my situation is special There is a data system that supports SQL-92 and JDBC interface However the SQL requets are pretty expensive, and in my application I need to retreive the same data multiple times and aggregate it ("group by") on different fields to show different dimensions of the same data. For example on one screen I have three tables that show the same set or records but aggregated by City (1st grid), by Population (2nd grid), by number of babies (3rd grid) This amounts to 3 SQL queries (which is very slow), UNLESS anyone of you can suggest any idea any library from apache commons or from google code, so that I can select all records into ResultSet and get 3 arrays of data group by different fields from this single ResultSet. Am I'm missing some obvious and unexpected solution to this problem?

    Read the article

  • Java: jaxb Generircs

    - by Mac
    How can I get jaxb to bind to my Vector? I cannot seem to get it to bind a Vector that contains generics as it complains that it cannot recognize my class "shape" or any of its subtypes.. "[javax.xml.bind.JAXBException: class shape.shape nor any of its super class is known to this context.]"? import java.util.Vector; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlAccessorType(XmlAccessType.NONE) @XmlRootElement(name = "XVector") public class XVector<shape> { private Vector<shape> q; public XVector() {} @XmlElement(name = "q") public Vector<shape> getVector() { return q; } public void setVector(Vector<shape> q) { this.q = q; } } I get the following errors: javax.xml.bind.MarshalException - with linked exception: [javax.xml.bind.JAXBException: class shape.Rectangle nor any of its super class is known to this context.] at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:317) at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.marshal(MarshallerImpl.java:243) at javax.xml.bind.helpers.AbstractMarshallerImpl.marshal(AbstractMarshallerImpl.java:75) public void saveFile(File filename) { try { FileOutputStream fout = new FileOutputStream(filename); objs.setVector(objVec); JAXBContext context = JAXBContext.newInstance(XVector.class); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(objs, fout); fout.close(); } catch (JAXBException e) { e.printStackTrace (); } catch (Exception ex) { JOptionPane.showMessageDialog(this, ex.toString(), "Error", JOptionPane.ERROR_MESSAGE); } }

    Read the article

  • How to give a custom ASP.NET control the ability to parse XML markup to a collection?

    - by Vilx-
    I'm writing a custom ASP.NET webcontrol and would like it to have a collection of custom items which can also be specified in the XML markup. Something like this: class MyControl: WebControl { public IList<MyItemType> MyItems { get; private set; } } And in the markup: <asd:MyControl runat="server" id="mc1"> <MyItems> <MyDerivedCustomItem asd="dsa"/> <MyOtherDerivedCustomItem asd="dsa"/> </MyItems> </asd:MyControl> How do I do this? I though this was all about implementing some interface on the collection or adding some special attributes to the property, but nothing I do seems to work.

    Read the article

  • List method creation

    - by Jonathan D
    I'm creating a list of my defined objects like so List<clock> cclocks = new List<clocks>(); for each object in the list i'm calling a method moveTime, like so foreach(clock c in cclocks) { c.moveTime(); } is the a way i can write some cleaver thing so i can call cclocks.moveTime(); it would then go though the list doing that method I guess I want to create a collection method? I'm guessing there must be some thing I can do I just don't know what. thanks for your help

    Read the article

  • Is there a way to transfrom a list of key/value pairs into a data transfer object

    - by weevie
    ...apart from the obvious looping through the list and a dirty great case statement! I've turned over a few Linq queries in my head but nothing seems to get anywhere close. Here's the an example DTO if it helps: class ClientCompany { public string Title { get; private set; } public string Forenames { get; private set; } public string Surname { get; private set; } public string EmailAddress { get; private set; } public string TelephoneNumber { get; private set; } public string AlternativeTelephoneNumber { get; private set; } public string Address1 { get; private set; } public string Address2 { get; private set; } public string TownOrDistrict { get; private set; } public string CountyOrState { get; private set; } public string PostCode { get; private set; } } We have no control over the fact that we're getting the data in as KV pairs, I'm afraid.

    Read the article

  • Re-ordering collection C#

    - by Adam
    Hi - I have a problem which I cant seem to find answer to through searches (either that or I am searching for the completely wrong thing!). I have a list of items called "Top 10" in a sortedlist item that is populated from my DB (SortedList where int is position and string is item). I want to be able to move items up & down the list order at the click of a button and then save the new order back to the DB. I am OK with the DB part it is just the re-ordering I am really struggling with - is a sortedlist the correct collection for this? Many thanks for any advice offered.

    Read the article

  • VB.NET - Find a Substring in an ArrayList, StringCollection or List(Of String)

    - by CJM
    I've got some code that creates a list of AD groups that the user is a member of, with the intention of saying 'if user is a member of GroupX then allow admin access, if not allow basic access'. I was using a StringCollection to store this list of Groups, and intended to use the Contains method to test for membership of my admin group, but the problem is that this method only compares the full string - but my AD groups values are formatted as cn=GroupX, etc.... I want to be easily able to determine if a particular substring (i.e. 'GroupX') appears in the list of groups. I could always iterate through the groups check each for a substring representing my AD group name, but I'm more interested in finding out if there is a 'better' way. Clearly there are a number of repositories for the list of Groups, and it appears that Generics (List(Of String)) are more commonly preferred (which I may well implement anyway) but there is no in-built means of checking for a substring using this method either. Any suggestions? Or should I just iterated through the list of groups?

    Read the article

  • How can I reduce the number of loops in this VIEW in Rails when using :collection?

    - by Angela
    I am using the :collection to go through all the Contacts that are part of a given Campaign. But within that Campaign I check for three different Models (each with their own partial). Feels like I am going through the list of Contacts 3x. How can I make this alot leaner? <h2>These are past due:</h2> <% @campaigns.each do |campaign| %> <h3>Campaign: <%= link_to campaign.name, campaign %></h3> <strong>Emails in this Campaign:</strong> <% for email in campaign.emails %> <h4><%= link_to email.title, email %> <%= email.days %> days</h4> <% @contacts= campaign.contacts.find(:all, :order => "date_entered ASC" )%> <!--contacts collection--> <!-- render the information for each contact --> <%= render :partial => "contact_email", :collection => @contacts, :locals => {:email => email} %> <% end %> Calls in this Campaign: <% for call in campaign.calls %> <h4><%= link_to call.title, call %> <%= call.days %> days</h4> <% @contacts= campaign.contacts.find(:all, :order => "date_entered ASC" )%> <!--contacts collection--> <!-- render the information for each contact --> <%= render :partial => "contact_call", :collection => @contacts, :locals => {:call => call} %> <% end %> Letters in this Campaign: <% for letter in campaign.letters %> <h4><%= link_to letter.title, letter %> <%= letter.days %> days</h4> <% @contacts= campaign.contacts.find(:all, :order => "date_entered ASC" )%> <!--contacts collection--> <!-- render the information for each contact --> <%= render :partial => "contact_letter", :collection => @contacts, :locals => {:letter => letter} %> <% end %> <% end %>

    Read the article

  • custom collection in property grid

    - by guyl
    Hi guys. I'm using this article as a reference to use custom collection in propertygrid: LINK When I open the collectioneditor and remove all items then I press OK, I get an exception if null. How can i solve that ? I am using: public T this[int index] { get { if (List.Count == 0) { return default(T); } else { return (T)this.List[index]; } } } as a getter for an item, of course if I have no object how can i restart the whole collection ? this is the whole code /// <summary> /// A generic folder settings collection to use in a property grid. /// </summary> /// <typeparam name="T">can be import or export folder settings.</typeparam> [Serializable] [TypeConverter(typeof(FolderSettingsCollectionConverter)), Editor(typeof(FolderSettingsCollectionEditor), typeof(UITypeEditor))] public class FolderSettingsCollection_New<T> : CollectionBase, ICustomTypeDescriptor { private bool m_bRestrictNumberOfItems; private int m_bNumberOfItems; private Dictionary<string, int> m_UID2Idx = new Dictionary<string, int>(); private T[] arrTmp; /// <summary> /// C'tor, can determine the number of objects to hold. /// </summary> /// <param name="bRestrictNumberOfItems">restrict the number of folders to hold.</param> /// <param name="iNumberOfItems">The number of folders to hold.</param> public FolderSettingsCollection_New(bool bRestrictNumberOfItems = false , int iNumberOfItems = 1) { m_bRestrictNumberOfItems = bRestrictNumberOfItems; m_bNumberOfItems = iNumberOfItems; } /// <summary> /// Add folder to collection. /// </summary> /// <param name="t">Folder to add.</param> public void Add(T t) { if (m_bRestrictNumberOfItems) { if (this.List.Count >= m_bNumberOfItems) { return; } } int index = this.List.Add(t); if (t is WriteDataFolderSettings || t is ReadDataFolderSettings) { FolderSettingsBase tmp = t as FolderSettingsBase; m_UID2Idx.Add(tmp.UID, index); } } /// <summary> /// Remove folder to collection. /// </summary> /// <param name="t">Folder to remove.</param> public void Remove(T t) { this.List.Remove(t); if (t is WriteDataFolderSettings || t is ReadDataFolderSettings) { FolderSettingsBase tmp = t as FolderSettingsBase; m_UID2Idx.Remove(tmp.UID); } } /// <summary> /// Gets ot sets a folder. /// </summary> /// <param name="index">The index of the folder in the collection.</param> /// <returns>A folder object.</returns> public T this[int index] { get { //if (List.Count == 0) //{ // return default(T); //} //else //{ return (T)this.List[index]; //} } } /// <summary> /// Gets or sets a folder. /// </summary> /// <param name="sUID">The UID of the folder.</param> /// <returns>A folder object.</returns> public T this[string sUID] { get { if (this.Count == 0 || !m_UID2Idx.ContainsKey(sUID)) { return default(T); } else { return (T)this.List[m_UID2Idx[sUID]]; } } } /// <summary> /// /// </summary> /// <param name="sUID"></param> /// <returns></returns> public bool ContainsItemByUID(string sUID) { return m_UID2Idx.ContainsKey(sUID); } /// <summary> /// /// </summary> /// <returns></returns> public String GetClassName() { return TypeDescriptor.GetClassName(this, true); } /// <summary> /// /// </summary> /// <returns></returns> public AttributeCollection GetAttributes() { return TypeDescriptor.GetAttributes(this, true); } /// <summary> /// /// </summary> /// <returns></returns> public String GetComponentName() { return TypeDescriptor.GetComponentName(this, true); } /// <summary> /// /// </summary> /// <returns></returns> public TypeConverter GetConverter() { return TypeDescriptor.GetConverter(this, true); } /// <summary> /// /// </summary> /// <returns></returns> public EventDescriptor GetDefaultEvent() { return TypeDescriptor.GetDefaultEvent(this, true); } /// <summary> /// /// </summary> /// <returns></returns> public PropertyDescriptor GetDefaultProperty() { return TypeDescriptor.GetDefaultProperty(this, true); } /// <summary> /// /// </summary> /// <param name="editorBaseType"></param> /// <returns></returns> public object GetEditor(Type editorBaseType) { return TypeDescriptor.GetEditor(this, editorBaseType, true); } /// <summary> /// /// </summary> /// <param name="attributes"></param> /// <returns></returns> public EventDescriptorCollection GetEvents(Attribute[] attributes) { return TypeDescriptor.GetEvents(this, attributes, true); } /// <summary> /// /// </summary> /// <returns></returns> public EventDescriptorCollection GetEvents() { return TypeDescriptor.GetEvents(this, true); } /// <summary> /// /// </summary> /// <param name="pd"></param> /// <returns></returns> public object GetPropertyOwner(PropertyDescriptor pd) { return this; } /// <summary> /// /// </summary> /// <param name="attributes"></param> /// <returns></returns> public PropertyDescriptorCollection GetProperties(Attribute[] attributes) { return GetProperties(); } /// <summary> /// Called to get the properties of this type. /// </summary> /// <returns></returns> public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list of employees for (int i = 0; i < this.List.Count; i++) { // Create a property descriptor for the employee item and add to the property descriptor collection CollectionPropertyDescriptor_New<T> pd = new CollectionPropertyDescriptor_New<T>(this, i); pds.Add(pd); } // return the property descriptor collection return pds; } public T[] ToArray() { if (arrTmp == null) { arrTmp = new T[List.Count]; for (int i = 0; i < List.Count; i++) { arrTmp[i] = (T)List[i]; } } return arrTmp; } } /// <summary> /// Enable to display data about a collection in a property grid. /// </summary> /// <typeparam name="T">Folder object.</typeparam> public class CollectionPropertyDescriptor_New<T> : PropertyDescriptor { private FolderSettingsCollection_New<T> collection = null; private int index = -1; /// <summary> /// /// </summary> /// <param name="coll"></param> /// <param name="idx"></param> public CollectionPropertyDescriptor_New(FolderSettingsCollection_New<T> coll, int idx) : base("#" + idx.ToString(), null) { this.collection = coll; this.index = idx; } /// <summary> /// /// </summary> public override AttributeCollection Attributes { get { return new AttributeCollection(null); } } /// <summary> /// /// </summary> /// <param name="component"></param> /// <returns></returns> public override bool CanResetValue(object component) { return true; } /// <summary> /// /// </summary> public override Type ComponentType { get { return this.collection.GetType(); } } /// <summary> /// /// </summary> public override string DisplayName { get { if (this.collection[index] != null) { return this.collection[index].ToString(); } else { return null; } } } public override string Description { get { return ""; } } /// <summary> /// /// </summary> /// <param name="component"></param> /// <returns></returns> public override object GetValue(object component) { if (this.collection[index] != null) { return this.collection[index]; } else { return null; } } /// <summary> /// /// </summary> public override bool IsReadOnly { get { return false; } } public override string Name { get { return "#" + index.ToString(); } } /// <summary> /// /// </summary> public override Type PropertyType { get { return this.collection[index].GetType(); } } public override void ResetValue(object component) { } /// <summary> /// /// </summary> /// <param name="component"></param> /// <returns></returns> public override bool ShouldSerializeValue(object component) { return true; } /// <summary> /// /// </summary> /// <param name="component"></param> /// <param name="value"></param> public override void SetValue(object component, object value) { // this.collection[index] = value; } }

    Read the article

  • Why doesn't ConcurrentQueue<T>.Count return 0 when IsEmpty == true?

    - by DanTup - Danny Tuppeny
    I was reading about the new concurrent collection classes in .NET 4 on James Michael Hare's blog, and the page talking about ConcurrentQueue<T> says: It’s still recommended, however, that for empty checks you call IsEmpty instead of comparing Count to zero. I'm curious - if there is a reason to use IsEmpty instead of comparing Count to 0, why does the class not internally check IsEmpty and return 0 before doing any of the expensive work to count? E.g.: public int Count { get { // Check IsEmpty so we can bail out quicker if (this.IsEmpty) return 0; // Rest of "expensive" counting code } } It seems strange to suggest this if it could be "fixed" so easily with no side-effects?

    Read the article

  • Is there an equivalent for ActiveRecord#find_by equivalent for C#?

    - by Benjamin Manns
    I'm originally a C# developer (as a hobby), but as of late I have been digging into Ruby on Rails and I am really enjoying it. Right now I am building an application in C# and I was wondering if there is any collection implementation for C# that could match (or "semi-match") the find_by method of ActiveRecord. What I am essentially looking for is a list that would hold Rectangles: class Rectangle { public int Width { get; set; } public int Height { get; set; } public String Name { get; set; } } Where I could query this list and find all entries with Height = 10, Width = 20, or name = "Block". This was done with ActiveRecord by doing a call similar to Rectangle.find_by_name('Block'). The only way I can think of doing this in C# is to create my own list implementation and iterate through each item manually checking each item against the criteria. I fear I would be reinventing the wheel (and one of poorer quality). Any input or suggestions is much appreciated.

    Read the article

  • Does The Clear Method On A Collection Release The Event Subscriptions?

    - by DaveB
    I have a collection private ObservableCollection<Contact> _contacts; In the constructor of my class I create it _contacts = new ObservableCollection<Contact>(); I have methods to add and remove items from my collection. I want to track changes to the entities in my collection which implement the IPropertyChanged interface so I subscribe to their PropertyChanged event. public void AddContact(Contact contact) { ((INotifyPropertyChanged)contact).PropertyChanged += new PropertyChangedEventHandler(Contact_PropertyChanged); _contacts.Add(contact); } public void AddContact(int index, Contact contact) { ((INotifyPropertyChanged)contact).PropertyChanged += new PropertyChangedEventHandler(Contact_PropertyChanged); _contacts.Insert(index, contact); } When I remove an entity from the collection, I unsubscribe from the PropertyChanged event. I am told this is to allow the entity to be garbage collected and not create memory issues. public void RemoveContact(Contact contact) { ((INotifyPropertyChanged)contact).PropertyChanged -= Contact_PropertyChanged; _contacts.Remove(contact); } So, I hope this is all good. Now, I need to clear the collection in one of my methods. My first thought would be to call _contacts.Clear(). Then I got to wondering if this releases those event subscriptions? Would I need to create my own clear method? Something like this: public void ClearContacts() { foreach(Contact contact in _contacts) { this.RemoveContact(contact); } } I am hoping one of the .NET C# experts here could clear this up for me or tell me what I am doing wrong.

    Read the article

< Previous Page | 13 14 15 16 17 18 19 20 21 22 23 24  | Next Page >