Search Results

Search found 5987 results on 240 pages for 'nested sets'.

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

  • rails nested attributes

    - by user342798
    I am using rails 3.0.0.beta3 and I am trying to implement form with nested attributes using :accepts_nested_attributes_for. My form is nested to three levels: Survey Question Answer. Survey has_many Questions, and Question has many Answers. Inside the Survey model, there is :accepts_nested_attributes_for :questions and inside the question mode, there is :accepts_nested_attributes_for :answers Everything is working fine except when I add a new answer to an existing question, it doesn't get created. However, if I make changes to the corresponding question while creating the answer, I can successfully create the answer. This example is exactly similar to a railscast: http://railscasts.com/episodes/197-nested-model-form-part-2 but doesn't work in rails3 (at least in my case). Please let me know if there is any issue with nested attributes in Rails 3. Thanks in advance.

    Read the article

  • undefined method `build_users' with nested models

    - by Cédric
    I've got into trouble with nested attributes. Here is my Account model : class Account < ActiveRecord::Base has_many :products has_many :blogs has_many :openings has_many :users has_one :logo, :class_name => "AccountPicture" has_one :address, :class_name => "AccountAddress" has_and_belongs_to_many :options accepts_nested_attributes_for :logo, :allow_destroy => true accepts_nested_attributes_for :address, :allow_destroy => true accepts_nested_attributes_for :users, :allow_destroy => true end And here is my User model : class User < ActiveRecord::Base belongs_to :account end As you can see, Account accepts nested attributes for logo, address, and users. While testing, i can use nested attributes for logo and address, but not for user. a = Account.new => #<Account id: nil, hostname: nil, subdomain: nil, name: nil, description: nil, base_line: nil, footer: nil, phone_number: nil, mobile_number: nil, email_address: nil, created_at: nil, updated_at: nil> # building the address works fine >> a.build_address => #<AccountAddress id: nil, account_id: nil, country: nil, state: nil, county: nil, city: nil, suburb: nil, zipcode: nil, street: nil, streetno: nil, longitude: nil, latitude: nil, error_code: nil> # building the users fails >> a.build_users NoMethodError: undefined method `build_users' for #<Account:0x7f6862a5f948> from /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/attribute_methods.rb:260:in `method_missing' from (irb):2 Thus, in my views, when i use the nested forms, i got this error back : User(#69850615730460) expected, got Array(#69850664775200) Any help would be appreciated. Thanks.

    Read the article

  • rails search nested set (categories and sub categories)

    - by bob
    Hello, I am using the http://github.com/collectiveidea/awesome_nested_set awesome nested set plugin and currently, if I choose a sub category as my category_id for an item, I can not search by its parent. Category.parent Category.Child I choose Category.child as the category that my item is in. So now my item has category_id of 4 stored in it. If I go to a page in my rails application, lets say teh Category page and I am on the Category.parent's page, I want to show products that have category_id's of all the descendants as well. So ideally i want to have a find method that can take into account the descendants. You can get the descendants of a root by calling root.descendants (a built in plugin method). How would I go about making it so I can query a find that gets the descendants of a root instead of what its doing now which is binging up nothing unless the product had a specific category_id of the Category.parent. I hope I am being clear here. I either need to figure out a way to create a find method or named_scope that can query and return an array of objects that have id's corresponding tot he descendants of a root OR if I have any other options, what are they? I thought about creating a field in my products table like parent_id which can keep track of the parent so i can then create two named scopes one finding the parent stuff and one finding the child stuff and chaining them. I know I can create a named scope for each child and chain them together for multiple children but this seems a very tedious process and also, if you add more children, you would need to specify more named scopes.

    Read the article

  • Alternative to Nested Loop For Comparison

    - by KGVT
    I'm currently writing a program that needs to compare each file in an ArrayList of variable size. Right now, the way I'm doing this is through a nested code loop: if(tempList.size()>1){ for(int i=0;i<=tempList.size()-1;i++) //Nested loops. I should feel dirty? for(int j=i+1;j<=tempList.size()-1;j++){ //*Gets sorted. System.out.println(checkBytes(tempList.get(i), tempList.get(j))); } } I've read a few differing opinions on the necessity of nested loops, and I was wondering if anyone had a more efficient alternative. At a glance, each comparison is going to need to be done, either way, so the performance should be fairly steady, but I'm moderately convinced there's a cleaner way to do this. Any pointers?

    Read the article

  • how to save nested form attributes to database

    - by siulamvictor
    I am not really understand how's the nested attributes work in Rails. I have 2 models, Accounts and Users. Accounts has_many Users. When a new user filled in the form, Rails reported User(#2164802740) expected, got Array(#2148376200) Is that Rails cannot read the nested attributes from the form? How can I fix it? How can I save the data from nested attributes form to database? Thanks all~ Here are the MVCs: Account Model class Account < ActiveRecord::Base has_many :users accepts_nested_attributes_for :users validates_presence_of :company_name, :message => "companyname is required." validates_presence_of :company_website, :message => "website is required." end User Model class User < ActiveRecord::Base belongs_to :account validates_presence_of :user_name, :message => "username too short." validates_presence_of :password, :message => "password too short." end Account Controller class AccountController < ApplicationController def new end def created end def create @account = Account.new(params[:account]) if @account.save redirect_to :action => "created" else flash[:notice] = "error!!!" render :action => "new" end end end Account/new View <h1>Account#new</h1> <% form_for :account, :url => { :action => "create" } do |f| %> <% f.fields_for :users do |ff| %> <p> <%= ff.label :user_name %><br /> <%= ff.text_field :user_name %> </p> <p> <%= ff.label :password %><br /> <%= ff.password_field :password %> </p> <% end %> <p> <%= f.label :company_name %><br /> <%= f.text_field :company_name %> </p> <p> <%= f.label :company_website %><br /> <%= f.text_field :company_website %> </p> <% end %> Account Migration class CreateAccounts < ActiveRecord::Migration def self.up create_table :accounts do |t| t.string :company_name t.string :company_website t.timestamps end end def self.down drop_table :accounts end end User Migration class CreateUsers < ActiveRecord::Migration def self.up create_table :users do |t| t.string :user_name t.string :password t.integer :account_id t.timestamps end end def self.down drop_table :users end end Thanks everyone. :)

    Read the article

  • Nested class or not nested class?

    - by eriks
    I have class A and list of A objects. A has a function f that should be executed every X seconds (for the first instance every 1 second, for the seconds instance every 5 seconds, etc.). I have a scheduler class that is responsible to execute the functions at the correct time. What i thought to do is to create a new class, ATime, that will hold ptr to A instance and the time A::f should be executed. The scheduler will hold a min priority queue of Atime. Do you think it is the correct implementation? Should ATime be a nested class of the scheduler?

    Read the article

  • Nested attributes in the index view?

    - by user283179
    How would I show one of many nested objects in the index view class Album < ActiveRecord::Base has_many: photos accepts_nested_attributes_for :photos, :reject_if => proc { |a| a.all? { |k, v| v.blank?} } has_one: cover accepts_nested_attributes_for :cover end class Album Controller < ApplicationController layout "mini" def index @albums = Album.find(:all, :include => [:cover,]).reverse respond_to do |format| format.html # index.html.erb format.xml { render :xml => @albums } end end This is what I have so fare. I just want to show a cover for each album. Any info on this would be a massive help!!

    Read the article

  • has_one | nested attributes -

    - by user283179
    How would I show one of many nested objects in the index view class Album < ActiveRecord::Base has_many: photos accepts_nested_attributes_for :photos, :reject_if => proc { |a| a.all? { |k, v| v.blank?} } has_one: cover accepts_nested_attributes_for :cover end class Album Controller < ApplicationController layout "mini" def index @albums = Album.find(:all, :include => [:cover,]).reverse respond_to do |format| format.html # index.html.erb format.xml { render :xml => @albums } end end This is what I have so fare. I just want to show a cover for each album. Any info on this would be a massive help!!

    Read the article

  • How Do I Prevent Rails From Treating Updated Nested Attributes Differently From New Nested Attribute

    - by James
    I am using rails3 beta3 and couchdb via couchrest. I am not using active record. I want to add multiple "Sections" to a "Guide" and add and remove sections dynamically via a little javascript. I have looked at all the screencasts by Ryan Bates and they have helped immensely. The only difference is that I want to save all the sections as an array of sections instead of individual sections. Basically like this: "sections" => [{"title" => "Foo1", "content" => "Bar1"}, {"title" => "Foo2", "content" => "Bar2"}] So, basically I need the params hash to look like that when the form is submitted. When I create my form I am doing the following: <%= form_for @guide, :url => { :action => "create" } do |f| %> <%= render :partial => 'section', :collection => @guide.sections %> <%= f.submit "Save" %> <% end %> And my section partial looks like this: <%= fields_for "sections[]", section do |guide_section_form| %> <%= guide_section_form.text_field :section_title %> <%= guide_section_form.text_area :content, :rows => 3 %> <% end %> Ok, so when I create the guide with sections, it is working perfectly as I would like. The params hash is giving me a sections array just like I would want. The problem comes when I want edit guide/sections and save them again because rails is inserting the id of the guide in the id and name of each form field, which is screwing up the params hash on form submission. Just to be clear, here is the raw form output for a new resource: <input type="text" size="30" name="sections[][section_title]" id="sections__section_title"> <textarea rows="3" name="sections[][content]" id="sections__content" cols="40"></textarea> And here is what it looks like when editing an existing resource: <input type="text" value="Foo1" size="30" name="sections[cd2f2759895b5ae6cb7946def0b321f1][section_title]" id="sections_cd2f2759895b5ae6cb7946def0b321f1_section_title"> <textarea rows="3" name="sections[cd2f2759895b5ae6cb7946def0b321f1][content]" id="sections_cd2f2759895b5ae6cb7946def0b321f1_content" cols="40">Bar1</textarea> How do I force rails to always use the new resource behavior and not automatically add the id to the name and value. Do I have to create a custom form builder? Is there some other trick I can do to prevent rails from putting the id of the guide in there? I have tried a bunch of stuff and nothing is working. Thanks in advance!

    Read the article

  • Accepts Nested Attributes For - edit form displays incorrect number of items ( + !map:ActiveSupport:

    - by Brightbyte8
    Hi, I have a teacher profile model which has many subjects (separate model). I want to add subjects to the profile on the same form for creating/editing a profile. I'm using accepts_nested_attributes for and this works fine for creation. However on the edit page I am getting a very strange error - instead of seeing 3 subjects (I added three at create and a look into the console confirms this), I see 12 subjects(!). #Profile model class Profile < ActiveRecord::Base has_many :subjects accepts_nested_attributes_for :subjects end #Subject Model class Subject < ActiveRecord::Base belongs_to :profile end #Profile Controller (only showing deviations from normal RESTFUL setup) def new @profile = Profile.new 3.times do @profile.subjects.build end end #Here's 1 of three parts of the subject output of = debug @profile errors: !ruby/object:ActiveRecord::Errors base: *id004 errors: !map:ActiveSupport::OrderedHash {} subjects: - &id001 !ruby/object:Subject attributes: exam: Either name: "7" created_at: 2010-04-15 10:38:13 updated_at: 2010-04-15 10:38:13 level: Either id: "31" profile_id: "3" attributes_cache: {} # Note that 3 of these attributes are displayed despite me seeing 12 subjects on screen Other info in case it's relevant. Rails: 2.3.5 Ruby 1.8.7 p149 HAML I've never had so much difficulty with a bug before - I've already lost about 8 hours to it. Would really appreciate any help! Thanks to any courageous takers Jack

    Read the article

  • Updating nested attributes causes duplicate entries

    - by params_noob
    I have a has_many and belongs_to relationship between Job and Address. When I try to update Job and Address in the same form, it updates job but creates a duplicate entry for Address. Am I missing something here? The Edit and Update Actions from Jobs: def edit @job = Job.find(params[:id]) end def update @job = Job.find(params[:id]) if @job.update_attributes(job_params) flash[:success] = "Job Updated" redirect_to current_user else render 'edit' end end The edit form: <h1>Edit Job Information</h1> <div class="row"> <div class="span6 offset3"> <%= form_for(@job) do |f| %> <%= render 'shared/error_messages' %> <%= f.label :recipient %> <%= f.text_field :recipient %> <%= f.label :age %> <%= f.text_field :age %> <%= f.label :gender %> <%= f.text_field :gender %> <%= f.label :ethnicity %> <%= f.text_field :ethnicity %> <%= f.label :height %> <%= f.text_field :height %> <%= f.label :weight %> <%= f.text_field :weight %> <%= f.label :hair %> <%= f.text_field :hair %> <%= f.label :eyes %> <%= f.text_field :eyes %> <%= f.label :other_info %> <%= f.text_field :other_info %> <h3> Address Information </h3> <%= f.fields_for :addresses do |address| %> <%= address.label :label, "Label" %> <%= address.text_field :label %> <%= address.label :addy, "Address" %> <%= address.text_field :addy %> <%= address.label :apt, "Apt/Suite/etc" %> <%= address.text_field :apt %> <%= address.label :city, "City" %> <%= address.text_field :city %> <%= address.label :state, "State" %> <%= address.text_field :state %> <%= address.label :zip, "Zip code" %> <%= address.text_field :zip %> <% end %> <%= f.label :instructions, "Service Instructions" %> <%= f.text_field :instructions %> <%= check_box_tag(:rush) %> <%= label_tag(:rush, "Rush?") %> <%= f.submit "Update Job", class: "btn btn-large btn-primary" %> <% end %> </div> </div>

    Read the article

  • intersection of three sets in python?

    - by Phil Brown
    Currently I am stuck trying to find the intersection of three sets. Now these sets are really lists that I am converting into sets, and then trying to find the intersection of. Here's what I have so far: for list1 in masterlist: list1=thingList1 for list2 in masterlist: list2=thingList2 for list3 in masterlist: list3=thingList3 d3=[set(thingList1), set(thingList2), set(thingList3)] setmatches c= set.intersection(*map(set,d3)) print setmatches and I'm getting set([]) Script terminated. I know there's a much simpler and better way to do this, but I can't find one...

    Read the article

  • Fastest way to perform subset test operation on a large collection of sets with same domain

    - by niktech
    Assume we have trillions of sets stored somewhere. The domain for each of these sets is the same. It is also finite and discrete. So each set may be stored as a bit field (eg: 0000100111...) of a relatively short length (eg: 1024). That is, bit X in the bitfield indicates whether item X (of 1024 possible items) is included in the given set or not. Now, I want to devise a storage structure and an algorithm to efficiently answer the query: what sets in the data store have set Y as a subset. Set Y itself is not present in the data store and is specified at run time. Now the simplest way to solve this would be to AND the bitfield for set Y with bit fields of every set in the data store one by one, picking the ones whose AND result matches Y's bitfield. How can I speed this up? Is there a tree structure (index) or some smart algorithm that would allow me to perform this query without having to AND every stored set's bitfield? Are there databases that already support such operations on large collections of sets?

    Read the article

  • C++ non-member functions for nested template classes

    - by beldaz
    I have been writing several class templates that contain nested iterator classes, for which an equality comparison is required. As I believe is fairly typical, the comparison is performed with a non-member (and non-friend) operator== function. In doing so, my compiler (I'm using Mingw32 GCC 4.4 with flags -O3 -g -Wall) fails to find the function and I have run out of possible reasons. In the rather large block of code below there are three classes: a Base class, a Composed class that holds a Base object, and a Nested class identical to the Composed class except that it is nested within an Outer class. Non-member operator== functions are supplied for each. These classes are in templated and untemplated forms (in their own respective namespaces), with the latter equivalent to the former specialised for unsigned integers. In main, two identical objects for each class are compared. For the untemplated case there is no problem, but for the templated case the compiler fails to find operator==. What's going on? #include <iostream> namespace templated { template<typename T> class Base { T t_; public: explicit Base(const T& t) : t_(t) {} bool equal(const Base& x) const { return x.t_==t_; } }; template<typename T> bool operator==(const Base<T> &x, const Base<T> &y) { return x.equal(y); } template<typename T> class Composed { typedef Base<T> Base_; Base_ base_; public: explicit Composed(const T& t) : base_(t) {} bool equal(const Composed& x) const {return x.base_==base_;} }; template<typename T> bool operator==(const Composed<T> &x, const Composed<T> &y) { return x.equal(y); } template<typename T> class Outer { public: class Nested { typedef Base<T> Base_; Base_ base_; public: explicit Nested(const T& t) : base_(t) {} bool equal(const Nested& x) const {return x.base_==base_;} }; }; template<typename T> bool operator==(const typename Outer<T>::Nested &x, const typename Outer<T>::Nested &y) { return x.equal(y); } } // namespace templated namespace untemplated { class Base { unsigned int t_; public: explicit Base(const unsigned int& t) : t_(t) {} bool equal(const Base& x) const { return x.t_==t_; } }; bool operator==(const Base &x, const Base &y) { return x.equal(y); } class Composed { typedef Base Base_; Base_ base_; public: explicit Composed(const unsigned int& t) : base_(t) {} bool equal(const Composed& x) const {return x.base_==base_;} }; bool operator==(const Composed &x, const Composed &y) { return x.equal(y); } class Outer { public: class Nested { typedef Base Base_; Base_ base_; public: explicit Nested(const unsigned int& t) : base_(t) {} bool equal(const Nested& x) const {return x.base_==base_;} }; }; bool operator==(const Outer::Nested &x, const Outer::Nested &y) { return x.equal(y); } } // namespace untemplated int main() { using std::cout; unsigned int testVal=3; { // No templates first typedef untemplated::Base Base_t; Base_t a(testVal); Base_t b(testVal); cout << "a=b=" << testVal << "\n"; cout << "a==b ? " << (a==b ? "TRUE" : "FALSE") << "\n"; typedef untemplated::Composed Composed_t; Composed_t c(testVal); Composed_t d(testVal); cout << "c=d=" << testVal << "\n"; cout << "c==d ? " << (c==d ? "TRUE" : "FALSE") << "\n"; typedef untemplated::Outer::Nested Nested_t; Nested_t e(testVal); Nested_t f(testVal); cout << "e=f=" << testVal << "\n"; cout << "e==f ? " << (e==f ? "TRUE" : "FALSE") << "\n"; } { // Now with templates typedef templated::Base<unsigned int> Base_t; Base_t a(testVal); Base_t b(testVal); cout << "a=b=" << testVal << "\n"; cout << "a==b ? " << (a==b ? "TRUE" : "FALSE") << "\n"; typedef templated::Composed<unsigned int> Composed_t; Composed_t c(testVal); Composed_t d(testVal); cout << "c=d=" << testVal << "\n"; cout << "d==c ? " << (c==d ? "TRUE" : "FALSE") << "\n"; typedef templated::Outer<unsigned int>::Nested Nested_t; Nested_t e(testVal); Nested_t f(testVal); cout << "e=f=" << testVal << "\n"; cout << "e==f ? " << (e==f ? "TRUE" : "FALSE") << "\n"; // Above line causes compiler error: // error: no match for 'operator==' in 'e == f' } cout << std::endl; return 0; }

    Read the article

  • C#/.NET Little Wonders: The Useful But Overlooked Sets

    - by James Michael Hare
    Once again we consider some of the lesser known classes and keywords of C#.  Today we will be looking at two set implementations in the System.Collections.Generic namespace: HashSet<T> and SortedSet<T>.  Even though most people think of sets as mathematical constructs, they are actually very useful classes that can be used to help make your application more performant if used appropriately. A Background From Math In mathematical terms, a set is an unordered collection of unique items.  In other words, the set {2,3,5} is identical to the set {3,5,2}.  In addition, the set {2, 2, 4, 1} would be invalid because it would have a duplicate item (2).  In addition, you can perform set arithmetic on sets such as: Intersections: The intersection of two sets is the collection of elements common to both.  Example: The intersection of {1,2,5} and {2,4,9} is the set {2}. Unions: The union of two sets is the collection of unique items present in either or both set.  Example: The union of {1,2,5} and {2,4,9} is {1,2,4,5,9}. Differences: The difference of two sets is the removal of all items from the first set that are common between the sets.  Example: The difference of {1,2,5} and {2,4,9} is {1,5}. Supersets: One set is a superset of a second set if it contains all elements that are in the second set. Example: The set {1,2,5} is a superset of {1,5}. Subsets: One set is a subset of a second set if all the elements of that set are contained in the first set. Example: The set {1,5} is a subset of {1,2,5}. If We’re Not Doing Math, Why Do We Care? Now, you may be thinking: why bother with the set classes in C# if you have no need for mathematical set manipulation?  The answer is simple: they are extremely efficient ways to determine ownership in a collection. For example, let’s say you are designing an order system that tracks the price of a particular equity, and once it reaches a certain point will trigger an order.  Now, since there’s tens of thousands of equities on the markets, you don’t want to track market data for every ticker as that would be a waste of time and processing power for symbols you don’t have orders for.  Thus, we just want to subscribe to the stock symbol for an equity order only if it is a symbol we are not already subscribed to. Every time a new order comes in, we will check the list of subscriptions to see if the new order’s stock symbol is in that list.  If it is, great, we already have that market data feed!  If not, then and only then should we subscribe to the feed for that symbol. So far so good, we have a collection of symbols and we want to see if a symbol is present in that collection and if not, add it.  This really is the essence of set processing, but for the sake of comparison, let’s say you do a list instead: 1: // class that handles are order processing service 2: public sealed class OrderProcessor 3: { 4: // contains list of all symbols we are currently subscribed to 5: private readonly List<string> _subscriptions = new List<string>(); 6:  7: ... 8: } Now whenever you are adding a new order, it would look something like: 1: public PlaceOrderResponse PlaceOrder(Order newOrder) 2: { 3: // do some validation, of course... 4:  5: // check to see if already subscribed, if not add a subscription 6: if (!_subscriptions.Contains(newOrder.Symbol)) 7: { 8: // add the symbol to the list 9: _subscriptions.Add(newOrder.Symbol); 10: 11: // do whatever magic is needed to start a subscription for the symbol 12: } 13:  14: // place the order logic! 15: } What’s wrong with this?  In short: performance!  Finding an item inside a List<T> is a linear - O(n) – operation, which is not a very performant way to find if an item exists in a collection. (I used to teach algorithms and data structures in my spare time at a local university, and when you began talking about big-O notation you could immediately begin to see eyes glossing over as if it was pure, useless theory that would not apply in the real world, but I did and still do believe it is something worth understanding well to make the best choices in computer science). Let’s think about this: a linear operation means that as the number of items increases, the time that it takes to perform the operation tends to increase in a linear fashion.  Put crudely, this means if you double the collection size, you might expect the operation to take something like the order of twice as long.  Linear operations tend to be bad for performance because they mean that to perform some operation on a collection, you must potentially “visit” every item in the collection.  Consider finding an item in a List<T>: if you want to see if the list has an item, you must potentially check every item in the list before you find it or determine it’s not found. Now, we could of course sort our list and then perform a binary search on it, but sorting is typically a linear-logarithmic complexity – O(n * log n) - and could involve temporary storage.  So performing a sort after each add would probably add more time.  As an alternative, we could use a SortedList<TKey, TValue> which sorts the list on every Add(), but this has a similar level of complexity to move the items and also requires a key and value, and in our case the key is the value. This is why sets tend to be the best choice for this type of processing: they don’t rely on separate keys and values for ordering – so they save space – and they typically don’t care about ordering – so they tend to be extremely performant.  The .NET BCL (Base Class Library) has had the HashSet<T> since .NET 3.5, but at that time it did not implement the ISet<T> interface.  As of .NET 4.0, HashSet<T> implements ISet<T> and a new set, the SortedSet<T> was added that gives you a set with ordering. HashSet<T> – For Unordered Storage of Sets When used right, HashSet<T> is a beautiful collection, you can think of it as a simplified Dictionary<T,T>.  That is, a Dictionary where the TKey and TValue refer to the same object.  This is really an oversimplification, but logically it makes sense.  I’ve actually seen people code a Dictionary<T,T> where they store the same thing in the key and the value, and that’s just inefficient because of the extra storage to hold both the key and the value. As it’s name implies, the HashSet<T> uses a hashing algorithm to find the items in the set, which means it does take up some additional space, but it has lightning fast lookups!  Compare the times below between HashSet<T> and List<T>: Operation HashSet<T> List<T> Add() O(1) O(1) at end O(n) in middle Remove() O(1) O(n) Contains() O(1) O(n)   Now, these times are amortized and represent the typical case.  In the very worst case, the operations could be linear if they involve a resizing of the collection – but this is true for both the List and HashSet so that’s a less of an issue when comparing the two. The key thing to note is that in the general case, HashSet is constant time for adds, removes, and contains!  This means that no matter how large the collection is, it takes roughly the exact same amount of time to find an item or determine if it’s not in the collection.  Compare this to the List where almost any add or remove must rearrange potentially all the elements!  And to find an item in the list (if unsorted) you must search every item in the List. So as you can see, if you want to create an unordered collection and have very fast lookup and manipulation, the HashSet is a great collection. And since HashSet<T> implements ICollection<T> and IEnumerable<T>, it supports nearly all the same basic operations as the List<T> and can use the System.Linq extension methods as well. All we have to do to switch from a List<T> to a HashSet<T>  is change our declaration.  Since List and HashSet support many of the same members, chances are we won’t need to change much else. 1: public sealed class OrderProcessor 2: { 3: private readonly HashSet<string> _subscriptions = new HashSet<string>(); 4:  5: // ... 6:  7: public PlaceOrderResponse PlaceOrder(Order newOrder) 8: { 9: // do some validation, of course... 10: 11: // check to see if already subscribed, if not add a subscription 12: if (!_subscriptions.Contains(newOrder.Symbol)) 13: { 14: // add the symbol to the list 15: _subscriptions.Add(newOrder.Symbol); 16: 17: // do whatever magic is needed to start a subscription for the symbol 18: } 19: 20: // place the order logic! 21: } 22:  23: // ... 24: } 25: Notice, we didn’t change any code other than the declaration for _subscriptions to be a HashSet<T>.  Thus, we can pick up the performance improvements in this case with minimal code changes. SortedSet<T> – Ordered Storage of Sets Just like HashSet<T> is logically similar to Dictionary<T,T>, the SortedSet<T> is logically similar to the SortedDictionary<T,T>. The SortedSet can be used when you want to do set operations on a collection, but you want to maintain that collection in sorted order.  Now, this is not necessarily mathematically relevant, but if your collection needs do include order, this is the set to use. So the SortedSet seems to be implemented as a binary tree (possibly a red-black tree) internally.  Since binary trees are dynamic structures and non-contiguous (unlike List and SortedList) this means that inserts and deletes do not involve rearranging elements, or changing the linking of the nodes.  There is some overhead in keeping the nodes in order, but it is much smaller than a contiguous storage collection like a List<T>.  Let’s compare the three: Operation HashSet<T> SortedSet<T> List<T> Add() O(1) O(log n) O(1) at end O(n) in middle Remove() O(1) O(log n) O(n) Contains() O(1) O(log n) O(n)   The MSDN documentation seems to indicate that operations on SortedSet are O(1), but this seems to be inconsistent with its implementation and seems to be a documentation error.  There’s actually a separate MSDN document (here) on SortedSet that indicates that it is, in fact, logarithmic in complexity.  Let’s put it in layman’s terms: logarithmic means you can double the collection size and typically you only add a single extra “visit” to an item in the collection.  Take that in contrast to List<T>’s linear operation where if you double the size of the collection you double the “visits” to items in the collection.  This is very good performance!  It’s still not as performant as HashSet<T> where it always just visits one item (amortized), but for the addition of sorting this is a good thing. Consider the following table, now this is just illustrative data of the relative complexities, but it’s enough to get the point: Collection Size O(1) Visits O(log n) Visits O(n) Visits 1 1 1 1 10 1 4 10 100 1 7 100 1000 1 10 1000   Notice that the logarithmic – O(log n) – visit count goes up very slowly compare to the linear – O(n) – visit count.  This is because since the list is sorted, it can do one check in the middle of the list, determine which half of the collection the data is in, and discard the other half (binary search).  So, if you need your set to be sorted, you can use the SortedSet<T> just like the HashSet<T> and gain sorting for a small performance hit, but it’s still faster than a List<T>. Unique Set Operations Now, if you do want to perform more set-like operations, both implementations of ISet<T> support the following, which play back towards the mathematical set operations described before: IntersectWith() – Performs the set intersection of two sets.  Modifies the current set so that it only contains elements also in the second set. UnionWith() – Performs a set union of two sets.  Modifies the current set so it contains all elements present both in the current set and the second set. ExceptWith() – Performs a set difference of two sets.  Modifies the current set so that it removes all elements present in the second set. IsSupersetOf() – Checks if the current set is a superset of the second set. IsSubsetOf() – Checks if the current set is a subset of the second set. For more information on the set operations themselves, see the MSDN description of ISet<T> (here). What Sets Don’t Do Don’t get me wrong, sets are not silver bullets.  You don’t really want to use a set when you want separate key to value lookups, that’s what the IDictionary implementations are best for. Also sets don’t store temporal add-order.  That is, if you are adding items to the end of a list all the time, your list is ordered in terms of when items were added to it.  This is something the sets don’t do naturally (though you could use a SortedSet with an IComparer with a DateTime but that’s overkill) but List<T> can. Also, List<T> allows indexing which is a blazingly fast way to iterate through items in the collection.  Iterating over all the items in a List<T> is generally much, much faster than iterating over a set. Summary Sets are an excellent tool for maintaining a lookup table where the item is both the key and the value.  In addition, if you have need for the mathematical set operations, the C# sets support those as well.  The HashSet<T> is the set of choice if you want the fastest possible lookups but don’t care about order.  In contrast the SortedSet<T> will give you a sorted collection at a slight reduction in performance.   Technorati Tags: C#,.Net,Little Wonders,BlackRabbitCoder,ISet,HashSet,SortedSet

    Read the article

  • Calculate a set of concatenated sets of n sets

    - by Andras Zoltan
    Okay - I'm not even sure that the term is right - and I'm sure there is bound to be a term for this - but I'll do my best to explain. This is not quite a cross product here, and the order of the results are absolutely crucial. Given: IEnumerable<IEnumerable<string>> sets = new[] { /* a */ new[] { "a", "b", "c" }, /* b */ new[] { "1", "2", "3" }, /* c */ new[] { "x", "y", "z" } }; Where each inner enumerable represents an instruction to produce a set of concatenations as follows (the order here is important): set a* = new string[] { "abc", "ab", "a" }; set b* = new string[] { "123", "12", "1" }; set c* = new string[] { "xyz", "xy", "x" }; I want to produce set ordered concatenations as follows: set final = new string { a*[0] + b*[0] + c*[0], /* abc123xyz */ a*[0] + b*[0] + c*[1], /* abc123xy */ a*[0] + b*[0] + c*[2], /* abc123x */ a*[0] + b*[0], /* abc123 */ a*[0] + b*[1] + c*[0], /* abc12xyz */ a*[0] + b*[1] + c*[1], /* abc12xy */ a*[0] + b*[1] + c*[2], /* abc12x */ a*[0] + b*[1], /* abc12 */ a*[0] + b*[2] + c*[0], /* abc1xyz */ a*[0] + b*[2] + c*[1], /* abc1xy */ a*[0] + b*[2] + c*[2], /* abc1x */ a*[0] + b*[2], /* abc1 */ a*[0], /* abc */ a*[1] + b*[0] + c*[0], /* ab123xyz */ /* and so on for a*[1] */ /* ... */ a*[2] + b*[0] + c*[0], /* a123xyz */ /* and so on for a*[2] */ /* ... */ /* now lop off a[*] and start with b + c */ b*[0] + c*[0], /* 123xyz */ /* rest of the combinations of b + c with b on its own as well */ /* then finally */ c[0], c[1], c[2]}; So clearly, there are going to be a lot of combinations! I can see similarities with Numeric bases (since the order is important as well), and I'm sure there are permutations/combinations lurking in here too. The question is - how to write an algorithm like this that'll cope with any number of sets of strings? Linq, non-Linq; I'm not fussed. Why am I doing this? Indeed, why!? In Asp.Net MVC - I want to have partial views that can be redefined for a given combination of back-end/front-end culture and language. The most basic of these would be, for a given base view View, we could have View-en-GB, View-en, View-GB, and View, in that order of precedence (recognising of course that the language/culture codes could be the same, so some combinations might be the same - a Distinct() will solve that). But I also have other views that, in themselves, have other possible combinations before culture is even taken into account (too long to go into - but the fact is, this algo will enable a whole bunch of really cool that I want to offer my developers!). I want to produce a search list of all the acceptable view names, iterate through the whole lot until the most specific match is found (governed by the order that this algo will produce these concatenations in) then serve up the resolved Partial View. The result of the search can later be cached to avoid the expense of running the algorithm all the time. I already have a really basic version of this working that just has one enumerable of strings. But this is a whole different kettle of seafood! Any help greatly appreciated.

    Read the article

  • determine if intersection of a set with conjunction of two other sets is empty

    - by koen
    For any three given sets A, B and C: is there a way to determine (programmatically) whether there is an element of A that is part of the conjunction of B and C? example: A: all numbers greater than 3 B: all numbers lesser than 7 C: all numbers that equal 5 In this case there is an element in set A, being the number 5, that fits. I'm implementing this as specifications, so this numerical range is just an example. A, B, C could be anything.

    Read the article

  • Determine the relative compliment of two IEnumerable<T> sets in .net

    - by SFun28
    Hi! Is there an easy way to get the relative compliment of two sets? Perhaps using LINQ? http://en.wikipedia.org/wiki/Complement_(set_theory) I have to find the relative compliment of a set A relative to B. Both A and B are of type HashSet but I think the algorithm could be made more generation (IEnumerable or even ISet)? I could use a solution in either vb.net or C#.

    Read the article

  • SQL - Counting sets of Field-B values for each Field-A value

    - by potrnd
    Hello, First of all sorry that I could not think of a more descriptive title. What I want to do is the following using only SQL: I have some lists of strings, list1, list2 and list3. I have a dataset that contains two interesting columns, A and B. Column A contains a TransactionID and column B contains an ItemID. Naturally, there can be multiple rows that share the same TransactionIDs. I need to catch those transactions that have at least one ItemID in each and every list (list1 AND list2 AND list3). I also need to count how many times does that happen for each transaction. [EDIT] That is, count how many full sets of ItemIDs there are for each TransactionID", "Full Set" being any element of the list1 with any element of the list2 with any element of the list3 I hope that makes enough sense, perhaps I will be able to explain it better with a clear head. Thanks in advance

    Read the article

  • Nested Classes: A useful tool or an encapsulation violation?

    - by Bryan Harrington
    So I'm still on the fence as to whether or not I should be using these or not. I feel its an extreme violation of encapsulation, however I find that I am able to achieve some degree of encapsulation while gaining more flexibility in my code. Previous Java/Swing projects I had used nested classes to some degree, However now I have moved into other projects in C# and I am avoid their use. How do you feel about nested classes?

    Read the article

  • Algorithm to match items be value into sets base on total

    - by Ben
    Given n sets of items. Each item has a value. The items in a set have similar values but vary by a small amount. The goal is to create new sets containing three items selected from the original sets such that the total of the values is within a given range. Only one item a source set can be selected. For example: If we have the following starting sets: Set A - { 4.0, 3.8, 4.2 } Set B - { 7.0, 6.8, 7.2 } Set C - { 1.0, 0.9, 1.1 } Set D - { 6.5, 6.4, 6.6 } Set E - { 2.5, 2.4, 2.6 } Goal is to create sets containing three elements such that the total is between 11.9 and 12.1. For example { 3.8, 7.2, 1.0 } There can be unused elements. Can someone suggest an algorithm for this problem?

    Read the article

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