LINQ sorting on List Object - Various Object Type

I try to sort a List<Object> where the Object are different classes but all share the same Property Name for instance.
I got a Base Class where Class A and Class B inherit from the Base Class.
So during the Linq query I cannot specify with object type this is.
Problem here "from ?????Entry_Global?????? list in Entries"
Thanks for helping.
////Entries is a List<Object> which consist of class object as following\\\\\
public abstract class EntryBase<T>
private string _Name;
public string Name
get { return this._Name; }
set { this.SetProperty(ref this._Name, value); }
public class Entry_Global : EntryBase<Entry_Global>
public class Entry_CC : EntryBase<Entry_CC>
private string _url; //Web url
public string Url
get { return this._url; }
set { this.SetProperty(ref this._url, value.Contains("http") ? value : "http://" + value); }
public List<Object> SortBy()
IEnumerable<KeyedList<string, object>> groupedEntryList = null;
//The proble reside in the fact that list is not only one type
//so when comes in the orderby "Name" it doesn't know Name
//or any other properties which are all common to all those class
//It does not want to convert Entry_CC or Entry_Global to EntryBase
groupedEntryList =
from ?????Entry_Global?????? list in Entries
orderby list.Name
orderby list.CategoryRef.Name
group list by list.CategoryRef.Name into listByGroup
select new KeyedList<string, object>(listByGroup);
return groupedEntryList.ToList<object>();

Entry_Global and Entry_CC don't share the same base class since EntryBase<Entry_Global> and EntryBase<Entry_CC> are two totally different types so you cannot cast the objects in the List<object> to a common base class in this case.
You could cast from object to dynamic though:
public List<Object> SortBy()
List<object> objects = new List<object>();
objects.Add(new Entry_Global { Name = "K" });
objects.Add(new Entry_CC { Name = "A" });
objects.Add(new Entry_Global { Name = "I" });
objects.Add(new Entry_CC { Name = "C" });
var sortedObjectsByName = (from o in objects
let t = (dynamic)o
orderby t.Name
select o).ToList();
return sortedObjectsByName;
The dynamic keyword makes a type bypass static type checking at compile-time:
https://msdn.microsoft.com/en-us/library/dd264736.aspx. This basically means that a dynamic type is considered to have any property of any name at compile time. Of course you will get an exception at runtime if the type doesn't have a Name property but
providied that all objects in the List<T> to be sorted are of type EntryBase<T> you will be safe as long as the EntryBase<T> type defines the Name property that you sort by.
Please remember to close your threads by marking helpful posts as answer and please start a new thread if you have a new question.

Similar Messages

  • Regarding Month sorting in List Map String, Object

    Dear All,
    i have a list which is- List<Map<String, Object>> results . What i need is i want to sort the 'results ' .The values in results, when i tried to print it are
    RESULTS :{Apr 2009}
    RESULTS :{August 2008}
    RESULTS :{December 2008}
    RESULTS :{Feb 2009}
    RESULTS :{Jan 2009}
    RESULTS :{Jun 2009}
    RESULTS :{Mar 2009}
    RESULTS :{May 2009}
    RESULTS :{Nov 2008}
    RESULTS :{October 2008}
    RESULTS :{Sep 2008}
    i want to sort the values according to the month. like jan 2008,feb 2008 etc .
    Somebody please help .
    Thanks in advanced .

    sha_2008 wrote:
    The output sholud be june 2008,Dec 2008, Mar 2009. ie according to the increase order of monthsThat doesn't make it any clearer, in the example "June 2008" and "Mar 2009" are in the same map. Do you want that map to appear both before and after "Dec 2008" which doesn't make sense or are you expecting to restructure the data. If so, I would suggest you use a SortedMap like;
    List<Map<String,Object>> maps = ...
    SortedMap<String, Object> results = new TreeMap<String, Object>(dateComparator);
    for(Map<String, Object> map: maps)
       results.putAll(map);BTW: is there any good reason your dates are Strings instead of Date objects which are much easier to sort?

  • How to identify various objects used in code

    Hi All,
    Can anyone tell me how can I list down various objects used in a program.
    For example in a report program if I am calling a function module, calling an include program, implementing a class and so on. Now I want to list down the objects used in the above program.
    Thanks in advance,
    Venkat

    This can get you started.
    DATA:
      code_rec(132),
      itab LIKE STANDARD TABLE OF code_rec.
    DATA:
      obj_text(40),
      it_search LIKE STANDARD TABLE OF obj_text.
    PARAMETERS:
      prog        TYPE sobj_name.
    START-OF-SELECTION.
      PERFORM search_table.
      REFRESH itab.
      READ REPORT prog INTO itab.
      CHECK sy-subrc = 0.
      LOOP AT itab INTO code_rec.
        TRANSLATE code_rec TO UPPER CASE.
        LOOP AT it_search INTO obj_text.
          SEARCH code_rec FOR obj_text.
          CHECK sy-subrc EQ 0.
          WRITE:/ 'Found ', obj_text, 'in', code_rec.
        ENDLOOP.
      ENDLOOP.
    *&      Form  search_table
    FORM search_table.
      REFRESH it_search.
      PERFORM add_a_search USING 'CALL FUNCTION'.
    ENDFORM.                    " search_table
    *&      Form  add_a_search
    FORM add_a_search USING  p_text.
      obj_text =  p_text.
      TRANSLATE obj_text TO UPPER CASE.
      APPEND obj_text TO it_search.
    ENDFORM.                    " add_a_search

  • Sorting a List object

    Hi!
    I have a List object or component (java.awt.List) in my app.
    I try to order it using Collections.sort(my_list) but I recieve this message which I dont understand:
    The method sort(List<T>) in the type Collections is not applicable for the arguments (List)
    By the way, I would like to order it using a numeric order, not an ascii order, so I guess I have to use "implements Comparable", but how can I use that if my List contains Strings?
    I mean, my List has:
    20 bla bla
    9 bla bla
    and I want this:
    9 bla bla
    20 bla bla bla
    Any advice?
    Thanks a lot for your time.
    Edited by: Ricardo_Ruiz_Lopez on Dec 26, 2007 9:27 AM

    You are mixing up two different kinds of Lists. One is the AWT List (java.awt.List) which is what you are using and can be thought of more as a visual component.
    http://java.sun.com/javase/6/docs/api/java/awt/List.html
    The other is the utility Collections List (java.util.List) which is purely a data construct.
    http://java.sun.com/javase/6/docs/api/java/util/List.html
    So, bottom line is, the Collections.sort( ) won't work with the AWT list. You'll have to extract your data model which I think may be a String[] and sort that, then possibly re-insert with add(String item, int index) (I'm not sure on this part).
    Edited by: Encephalopathic on Dec 26, 2007 9:44 AM

  • Sorting a list of different class objects

    Hi All ,
    How to sort a List a.which contains objects of different Classes, b. objects of same class . Is it possible to sort these by implementing Comparable interface .
    Thanks ,
    Rajesh Reddy

    rajeshreddyk wrote:
    Hi All ,
    How to sort a List a.which contains objects of different Classes, b. objects of same class . Is it possible to sort these by implementing Comparable interface .Well, if objects of different classes are kept in the same List and you want to sort them together they at least have that in common. They're Comparable-able. -:) To manifest that the different classes could all implement a Comparableable interface (or maybe Intercomparable would be a better choise of name.)

  • How to get list of custom objects used in abap report program?

    Hi friends,
    I have a requirement in which I have to scan the entire abap report and retrieve list of custom objects used in it for example custom tables, data elements, structures, table types etc,. Is there any provision in SAP like fuction modules to do this functionality?  As of now I am coding everything manually where so many possibilities are there for all kinds of objects. Provide your answers and suggestions...
    Thanks,
    Nastera

    Hi,
    The best way to do this is environment analysis. Follow the steps:
    1. Open se38, type in the program name (don't click on on display/change or create button, stay on first screen only)
    2. Click on environment analysis button (hot key SHIFT+F4)
    3. It will throw a pop-up, which will ask for type of object you want to see, which are linked /used by this program. select all (or may be if you are only interested in Tables, then select table only)
    4. Hit 'Enter'
    You will get the full list of all objects used in this report program. Just note down the one which starts with Z or Y and that's it.
    Cheers,
    Anid

  • Creating smartform from attachment list of service object

    Hi,
       How can i create a smartform containing attachment list from generic object services(active workflow Box) in tcode VA02, Also let me know in which table this attachment lists are stored.
    Thanks,
       JP

    I found following Solution:
    I copied the following classes and changed them in some way to fit my requirements:
    1.CL_GOS_ATTACHMENTS
    2.CL_GOS_SRV_ATTACHMENT_LIST
    3.CL_LIST_BROWSER
    Changes to the Classes:
    1.Type of the attribute GO_INSTANCE changed to ZCL_GOS_ATTACHMENTS.
       Changed method INIT_BROWSER:
    go_browser ?=
        zcl_list_browser=>zcreate_browser( cl_browser=>gc_list_browser ).
    2.Type of the attribute GO_ATTACHMENT_LIST changed to ZCL_GOS_ATTACHMENTS
    3. Copied Method CREATE_BROWSER of Class CL_BROWSER to ZCREATE_BROWSER:
    method zcreate_browser.
      case ip_btype.
        when gc_list_browser.
          *create object ro_browser type zcl_list_browser.*
        when gc_tree_browser.
          create object ro_browser type cl_tree_column_browser.
        when others.
          raise exception type cx_sobl_browser
            exporting
              gp_error = cx_sobl_browser=>gc_wrong_type
          exit.
      endcase.
    endmethod.
    Modified the code of method ___DISPLAY to my needs.

  • Sort table of objects by object attribute

    Hi all,
    I would like to write method for sorting table of objects. Sorting will be according selected attribute of object.
    My problem is that when I have dynamic data, I'm not able to access attributes of object. Here is example in code. Problematic lines are commented.
    If you have any idea how to solve it, I will be very happy.
    CLASS lcl_reflection DEFINITION CREATE PUBLIC.
      PUBLIC SECTION.
        CLASS-METHODS: sort_object_table_by_field IMPORTING field_name   TYPE char72
                                                            direction    TYPE c DEFAULT 'A'
                                                  CHANGING  object_table TYPE table.
    ENDCLASS.                    "lcl_reflection DEFINITION
    CLASS lcl_reflection IMPLEMENTATION.
      METHOD sort_object_table_by_field.
        DATA: obj_type_desc   TYPE REF TO cl_abap_refdescr,
              cls_type_desc   TYPE REF TO cl_abap_classdescr,
              tab_type_desc   TYPE REF TO cl_abap_tabledescr,
              elm_type_desc   TYPE REF TO cl_abap_elemdescr,
              struc_type_desc TYPE REF TO cl_abap_structdescr,
              line            TYPE REF TO data,
              tab             TYPE REF TO data,
              object          TYPE REF TO data,
              lt_component TYPE cl_abap_structdescr=>component_table,
              ls_component LIKE LINE OF lt_component.
        FIELD-SYMBOLS: <object> TYPE any,
                       <tab>    TYPE table,
                       <line>   TYPE any,
                       <value>  TYPE any.
        READ TABLE object_table INDEX 1 ASSIGNING <object>.
        cls_type_desc ?= cl_abap_classdescr=>describe_by_object_ref( <object> ).
        elm_type_desc ?= cls_type_desc->get_attribute_type( field_name ).
        obj_type_desc ?= cl_abap_refdescr=>create( cls_type_desc ).
        UNASSIGN <object>.
        ls_component-name = 'key'.
        ls_component-type = elm_type_desc.
        APPEND ls_component TO lt_component.
        ls_component-name = 'object'.
        ls_component-type ?= obj_type_desc.
        APPEND ls_component TO lt_component.
        struc_type_desc ?= cl_abap_structdescr=>create( lt_component ).
        tab_type_desc ?= cl_abap_tabledescr=>create( p_line_type  = struc_type_desc
                                                     p_table_kind = cl_abap_tabledescr=>tablekind_std
                                                     p_unique     = abap_false ).
        REFRESH lt_component.
        CLEAR ls_component.
        CREATE DATA line TYPE HANDLE struc_type_desc.
        CREATE DATA tab TYPE HANDLE tab_type_desc.
        CREATE DATA object TYPE HANDLE obj_type_desc.
        ASSIGN tab->* TO <tab>.
        ASSIGN line->* TO <line>.
        ASSIGN object->* TO <object>.
        LOOP AT object_table REFERENCE INTO object.
          APPEND INITIAL LINE TO <tab> REFERENCE INTO line.
          ASSIGN object->* TO <value>.
          ASSIGN line->* TO <line>.
    *      <line>-key = <value>->(field_name).
    *      <line>-object = object.
        ENDLOOP.
    *    SORT <tab> BY key.
    *    LOOP AT <tab> REFERENCE INTO line.
    *      APPEND INITIAL LINE TO object_table REFERENCE INTO object.
    *      object = line-object.
    *    ENDLOOP.
      ENDMETHOD.                    "sort_object_table_by_field
    ENDCLASS.                    "lcl_reflection IMPLEMENTATION

    Ok guys, it's solved. It was little bit more complicated then I expected. Thanks for you help.
    METHOD sort_object_table_by_field.
        TYPES: t_object TYPE REF TO object.
        DATA: obj_type_desc   TYPE REF TO cl_abap_refdescr,
              cls_type_desc   TYPE REF TO cl_abap_classdescr,
              tab_type_desc   TYPE REF TO cl_abap_tabledescr,
              elm_type_desc   TYPE REF TO cl_abap_elemdescr,
              struc_type_desc TYPE REF TO cl_abap_structdescr,
              r_line          TYPE REF TO data,
              r_tab           TYPE REF TO data,
              r_object        TYPE REF TO data,
              r_obj           TYPE REF TO data,
              lt_component TYPE cl_abap_structdescr=>component_table,
              ls_component LIKE LINE OF lt_component.
        FIELD-SYMBOLS: <object>    TYPE any,
                       <obj>       TYPE REF TO object,
                       <tab>       TYPE table,
                       <line>      TYPE any,
                       <key>       TYPE any,
                       <fs_key>    TYPE any,
                       <fs_object> TYPE any.
        READ TABLE object_table INDEX 1 ASSIGNING <object>.
        cls_type_desc ?= cl_abap_classdescr=>describe_by_object_ref( <object> ).
        elm_type_desc ?= cls_type_desc->get_attribute_type( field_name ).
        obj_type_desc ?= cl_abap_refdescr=>create( cls_type_desc ).
        UNASSIGN <object>.
        ls_component-name = 'key'.
        ls_component-type = elm_type_desc.
        APPEND ls_component TO lt_component.
        ls_component-name = 'object'.
        ls_component-type ?= obj_type_desc.
        APPEND ls_component TO lt_component.
        struc_type_desc ?= cl_abap_structdescr=>create( lt_component ).
        tab_type_desc ?= cl_abap_tabledescr=>create( p_line_type  = struc_type_desc
                                                     p_table_kind = cl_abap_tabledescr=>tablekind_std
                                                     p_unique     = abap_false ).
        REFRESH lt_component.
        CLEAR ls_component.
        CREATE DATA r_line TYPE HANDLE struc_type_desc.
        CREATE DATA r_tab TYPE HANDLE tab_type_desc.
        CREATE DATA r_object TYPE HANDLE obj_type_desc.
        CREATE DATA r_obj TYPE REF TO object.
        ASSIGN r_tab->* TO <tab>.
        LOOP AT object_table REFERENCE INTO r_object.
          APPEND INITIAL LINE TO <tab> REFERENCE INTO r_line.
          ASSIGN r_object->* TO <object>.
          ASSIGN r_obj->* TO <obj>.
          MOVE <object> TO <obj>.
          ASSIGN <obj>->(field_name) TO <key>.
          ASSIGN r_line->* TO <line>.
          ASSIGN COMPONENT 'KEY' OF STRUCTURE <line> TO <fs_key>.
          ASSIGN COMPONENT 'OBJECT' OF STRUCTURE <line> TO <fs_object>.
          <fs_object> = <object>.
          <fs_key> = <key>.
        ENDLOOP.
        DATA: sort_field TYPE fieldname.
        sort_field = 'KEY'.
        SORT <tab> BY (sort_field).
        REFRESH object_table.
        LOOP AT <tab> REFERENCE INTO r_line.
          APPEND INITIAL LINE TO object_table REFERENCE INTO r_object.
          ASSIGN r_line->* TO <line>.
          ASSIGN r_object->* TO <object>.
          ASSIGN COMPONENT 'OBJECT' OF STRUCTURE <line> TO <fs_object>.
          <object> = <fs_object>.
        ENDLOOP.
      ENDMETHOD.

  • Dispute Case - Linked Objects- Various- URL

    Hello,
    We have a requirement to create a Dispute Case through a custom interface program. We have been doing this using BAPI_DISPUTE_CREATE.
    Now, I need to programmatically link a URL to Dispute Case -> Linked Objects->Various->URL. An custom element type for u2018URLu2019 was configured in the Registry for this in our SAP system.
    This is usually achieved programatically using the tables parameter OBJECTS of the BAPI. We have to pass the OBJ TYPE & KEY to this parameter.
    Since configuration does not allow the BOR_TYPE to be defined on tab u2018Connection Parametersu2019 of the Element Type URL in the Registry, what OBJTYPE and KEY works for this?
    Thanks,
    Smitha/Aneel

    Hello Andy,
    I have a question. We're also trying to use BAPI_DISPUTE_CREATE in order to create dispute cases, but the function needs a unique GUID number in order to create the dispute case. How did you manage to maintain this guid number?
    Because of this problem, we started using the function UDM_DC_CREATE, which generates a GUID itself, if you do not maintain one.
    Sorry for the inconveince, the problem was because of a wrong attribute, I can create a dispute case with this function without maintaining the guid id.
    Edited by: Karabiber Kerem on May 21, 2010 11:03 AM

  • List with multiple objects using Comparator

    Hi,
    I have a comparator to sort the fields of 2 objects. I have a resultlist which contains the CustomerAddressVO which contains the properties of both
    Customer and Address entities List resultList<CustomerAddressVO>.
    This CustomerAddressVO.java in turn have
    private long id
    private Customer customer;
    private Address address;
    Where Customer.java
    will have properties of customer
    Where Address.java
    will have properties of address
    Now i need to use the comparator for customer.getName() asc and address.id() desc, as i have mentioned the resultList doesn't directly contain this object as it contains CustomerAddressVO which in turn have those two object Customer and Address. Hence unless you iterate the list and retrieve the respective objects (customer, address) you cannot do the sorting through comparator. In such case how we can go about it. If you iterate the list also how we can pass the respective object to the compare() ? And more importantly we need to sort the columns of 2 different entites? Please clarify how we can go about it?
    Thanks.

    You can still do the sorting through a Comparator
    The compare method should take
    public int compare(CustomerAddressVO o1, CustomerAddressVO o2) { //..so you can then do
    01.getCustomer().getName();
    //and
    o1.getAddress().getId() together with relevant null checks

  • Sort by arbitrary value of object inside Map

    I have a HashMap full of user objects, let's say. I want to sort the user objects in different ways. So if the user object contains name, age, height, weight, etc., I need to sort on any one of those at runtime.
    I've seen some example in the forums for sorting a HashMap by value (involves creating a new structure, which is fine), but I guess I need to write a comparator that digs INTO the objects and compares based on properties INSIDE the object. Is this simple to do? Any elegant solution for this? I'm sure I could brute force hack this, but I wanted to use Colleciton and Comparator if at all possible.

    Example without any 3rd party libraries (but please do):import java.beans.BeanInfo;
    import java.beans.Introspector;
    import java.beans.PropertyDescriptor;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.List;
    public class Test {
        // don't use this, use something like BeanUtils
        // this just serves as a quick example
        private static Object getProperty(Object bean, String propertyName) {
            Object property = null;
            try {
                BeanInfo beanInfo = Introspector.getBeanInfo (bean.getClass ());
                PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors ();
                for (PropertyDescriptor propertyDescriptor: propertyDescriptors) {
                    if (propertyDescriptor.getName ().equals (propertyName)) {
                        property = propertyDescriptor.getReadMethod ().invoke (bean);
                        break;
            } catch (Exception exception) {}
            return property;
        public static class PropertyComparator<T> implements Comparator<T> {
            private String propertyName;
            public PropertyComparator (String propertyName) {
                this.propertyName = propertyName;
            public int compare (T a, T b) {
                Object valueA = getProperty (a, propertyName);
                Object valueB = getProperty (b, propertyName);
                // yet again - quite dirty [and not production ready :)], since null isn't instanceof anything
                if (! (valueA instanceof Comparable) || ! (valueB instanceof Comparable)) {
                    throw new IllegalStateException ();
                return ((Comparable) valueA).compareTo (valueB);
        public static void main (String... parameters) {
            List<Person> queen = new ArrayList<Person> ();
            queen.add (new Person ("Freddie", "Mercury"));
            queen.add (new Person ("Brian", "May"));
            queen.add (new Person ("John", "Deacon"));
            queen.add (new Person ("Roger", "Taylor"));
            System.out.println (queen);
            Collections.sort (queen, new PropertyComparator<Person> ("firstName"));
            System.out.println (queen);
            Collections.sort (queen, new PropertyComparator<Person> ("lastName"));
            System.out.println (queen);       
        private static class Person {
            private String firstName;
            private String lastName;
            public Person (String firstName, String lastName) {
                this.firstName = firstName;
                this.lastName = lastName;
            public String getFirstName () {
                return firstName;
            public String getLastName () {
                return lastName;
            @Override
            public String toString () {
                return String.format ("%s %s", firstName, lastName);
    }(This sorts a list, not a map. I'm sure you'll be able to adapt it to your situation.)

  • Cannot Cast List ? extends Object as List Object

    I apologize if this is a common question but I could not seem to find the proper set of search terms that yielded an answer.
    Basically I have an RMI application and on the 'middle-tier' I would like to pass around references to the implementation objects and only convert to the interface type when dealing with them over RMI (I never pass an object back to the middle-tier).
    public interface Questionnaire implements Remote {
        public List<? extends Comment> getComments() throws RemoteException;
    public class QuestionnaireImpl extends UnicastRemoteObject implements Questionnaire {
        public List<CommentImpl> getComments() {...}
    }This works fine, the issue arises when I try to do the following:
    public List<Comment> getComments(int questionnaireId) throws RemoteException {
        return classLoader.getQuestionnaire(questionnaireId).getComments();
    }The compiler issues a Type mismatch: cannot convert from List<capture#8-of ? extends Comment> to List<Comment> Which I find perplexing as the compiler can assure that at the very least it is a List of Comment objects.

    public List<? extends Comment> getComments() throws RemoteException;
    public List<Comment> getComments(int questionnaireId) throws RemoteException {
    return classLoader.getQuestionnaire(questionnaireId).getComments();
    The compiler issues a Type mismatch: cannot convert from List<capture#8-of ? extends Comment> to List<Comment> Which I find perplexing as the compiler can assure that at the very least it is a List of Comment objects.Yes, however Java's generics work correctly to prevent you from shooting yourself in the foot. If you have a List<Superclass> pointing at a List<Subclass>, you would be entirely within your rights to try to store an object that is not castable to Subclass in it, this breaks type safety, so the compiler will not let you do it.
    Instead, create a new List<Supertype> and copy over the elements from the list returned by getComments(). There is a constructor that will do this for you.

  • Query List of Custom Objects

    I'm unable to find a concrete answer on how to query an Object when it is contained within a List. Perhaps it's in the documentation or forums, but I haven't found it. What I have is a Building Object that contains a List<Room> rooms, and each Room has its own attributes like typeCode. Our cache contains Building Objects indexed by its own key. Now I want to write a Filter to locate 1 to many Building Objects that have a Room with a specific typeCode, say "2DB".
    I've tried an EqualsFilter with "2DB" and passing it a ValueExtractor that navigates the Building like: rooms.typeCode. I expect the Building getRooms() method to be called, which returns a List<Room>, and then reflection to evaluate the List contents to call getTypeCode() on each Room instance. Instead, I see errors because getTypeCode() doesn't exist on java.util.ArrayList. No kidding.
    How do I get the framework to dive inside the List and evaluate the Room instances inside it? All examples I've seen are for simple collections, like List<String> or List<Integer>, whereas I have a List<FooBar>.

    Hi,
    you would need to write a custom extractor to achieve this as the out-of-the-box extractors don't support invocation chaining across collections (i.e. extracting a collection created by extracting attributes from collection elements).
    something like this:
    import java.io.IOException;
    import java.lang.reflect.Array;
    import java.util.ArrayList;
    import java.util.Collection;
    import com.tangosol.io.pof.PofReader;
    import com.tangosol.io.pof.PofWriter;
    import com.tangosol.io.pof.PortableObject;
    import com.tangosol.util.ValueExtractor;
    public class TwoLevelChainExtractor implements ValueExtractor, PortableObject {
       private ValueExtractor extractorReturningCollection;
       private ValueExtractor extractorExtractingFromCollectionElement;
        * This is for the POF deserialization.
       public TwoLevelChainExtractor() {
       public TwoLevelChainExtractor(ValueExtractor extractorReturningCollection, ValueExtractor extractorExtractingFromCollectionElement) {
          this.extractorReturningCollection = extractorReturningCollection;
          this.extractorExtractingFromCollectionElement = extractorExtractingFromCollectionElement;
       @Override
       public Object extract(Object obj) {
          Object interim = extractorReturningCollection.extract(obj);
          Collection res = new ArrayList();
          ValueExtractor innerExtractor = extractorExtractingFromCollectionElement;
          if (interim instanceof Collection) {
             for (Object element : (Collection) interim) {
                res.add(innerExtractor.extract(element));
          } else if (interim instanceof Object[]) {
             for (Object element : (Object[]) interim) {
                res.add(innerExtractor.extract(element));
          } else {
             Class<? extends Object> cls = interim.getClass();
             if (cls.isArray()) {
                // primitive array
                int count = Array.getLength(interim);
                for (int i=0; i<count; ++i) {
                   Object boxedPrimitive = Array.get(interim, i);
                   res.add(innerExtractor.extract(boxedPrimitive));
             } else {
                res.add(innerExtractor.extract(interim));
          return res;
       @Override
       public void readExternal(PofReader reader) throws IOException {
          extractorReturningCollection = (ValueExtractor) reader.readObject(0);
          extractorExtractingFromCollectionElement = (ValueExtractor) reader.readObject(1);
       @Override
       public void writeExternal(PofWriter writer) throws IOException {
          writer.writeObject(0, extractorReturningCollection);
          writer.writeObject(1, extractorExtractingFromCollectionElement);
       // equals() and hashCode() are required to be able to use this extractor to create indexes, where the extractor acts as a key in a hash-map
       @Override
       public int hashCode() {
          final int prime = 31;
          int result = 1;
          result = prime * result
                + ((extractorExtractingFromCollectionElement == null) ? 0 : extractorExtractingFromCollectionElement.hashCode());
          result = prime * result + ((extractorReturningCollection == null) ? 0 : extractorReturningCollection.hashCode());
          return result;
       @Override
       public boolean equals(Object obj) {
          if (this == obj)
             return true;
          if (obj == null)
             return false;
          if (getClass() != obj.getClass())
             return false;
          TwoLevelChainExtractor other = (TwoLevelChainExtractor) obj;
          if (extractorExtractingFromCollectionElement == null) {
             if (other.extractorExtractingFromCollectionElement != null)
                return false;
          } else if (!extractorExtractingFromCollectionElement.equals(other.extractorExtractingFromCollectionElement))
             return false;
          if (extractorReturningCollection == null) {
             if (other.extractorReturningCollection != null)
                return false;
          } else if (!extractorReturningCollection.equals(other.extractorReturningCollection))
             return false;
          return true;
    }Afterwards you can just use this extractor to extract a collection of type codes from rooms:
    ValueExtractor roomsTypeCodes = new TwoLevelChainExtractor(new ReflectionExtractor("getRooms"), new ReflectionExtractor("getTypeCode"));You can use this roomsTypeCodes and a ContainsFilter or ContainsAnyFilter to achieve what you want.
    You can implementing similar stuff for POF extraction by leveraging the PofValueParser class in an EntryExtractor subclass.
    Best regards,
    Robert

  • Representing list of polymophic objects in db

    Let's suppose I have a list of derived objects from some base:
    class Circle : public Shape;
    class Rectangle : public Shape;
    There is object, which has vector of Shape * as member variable:
    class Screen {
    std::vector<Shape *> shapes_;
    But now I need to persist this in database (PostgreSQL to be precise). Only way I thought of is to have table per class, something like this:
    table screen ();
    table circle (
    int screen_id;
    table rectangle (
    int screen_id;
    And after retrieving from object of type Screen do query for Circles and Rectangles with screen.id. Should be doable.
    However I fear that when number of types grows (and it will), it would mean many db queries for just one object retrieval/persist.
    Right know we'll have about 10 types I think? That's 11 db queries just to retrieve one Screen object.
    So my questing is, is there better way to achieve my goal? I'm fine with redesigning my code if needed, I just would like some O(1) solution in correlation to number of types (my solution is O(n) ).
    Thank you guys ^_^
    NOTE: based on comment I'm adding that tables of Circles and Rectangles etc. will be used
    only to put together Screen object. I don't access (look-up, retrieve, persist, ...) to them individually, only as parts of Screen(s). They don't even have to be in their own table. Just didn't find a way to nicely put it all together :/

    All you need is one table, with a simple design. You need
    A field for the uid
    Possibly a field for a timestamp (you may need that, you may not, don't know your particular circumstances).
    A field in which you serialize the Screen object and all the Shapes it contains.
    That means just one write to save and one read to recover the Screen and its shapes. Why do more, given how simple your requirements are?
    I recommend you serialize to a json format. Postgresql now has a JSON data type and JSON operators and functions. So you can validate and examine the serialized data in the db if you want to, without having to extract and normalize it.
    Other benefits of this approach:
    If you later decide to serialize somewhere else (into a file or memory cache, for example), it would require minimal change to the code.
    No need to change your db schema if you add new types of Shapes or change the structure of any existing objects.

  • Have an object as return type in a method in the WebDynproComponent

    Hello together.
    I've wrote an EJB in which is a method that read out a DB Table XYZ. In this EJB also are methods to search a single entry.
    In my WebDynpro applixcation i have a method in the Component that access the EJB and retrive the single entry for example. In the View implemantation i call the method from the "WEbDynPro component" which have a string as return type.
    Is it possible to have an object as return type?
    public java.lang.String sr( int KVNR )
        //@@begin sr()
        KVNummerDTO kvnrObject = new KVNummerDTO();
        String Kasse = "";
          try
              KVNRSessionLocal kVNummerSessionLocal = kVNRSessionLocalHome.create();
              kvnrObject = kVNummerSessionLocal.getKVNummer(KVNR);
              Kasse = kvnrObject.getKasse();
          catch (Exception e)
               e.printStackTrace();
               wdComponentAPI.getMessageManager().reportException(e.getMessage(), true);
          return Kasse;
        //@@end
    I want to return kvnrObject  and not only a string!

    Hello Micheal,
    While Creating a method in front of the return type click on the browse and select Java Native Type Radio Button and again click on the browse button available there. Type the name of the class in the class in it and you can select the return type. If it is a user made class then first the required Java files under the path Resources>src>packages><create a folder>java file. Then build the project so that the class name is visible in list while selecting the return type.
    Regards,
    Ardhendu

Maybe you are looking for

  • Invoice Issue

    Hi Gurus,   I am doing a PO, say 36000rs for 100 KG materials with a tax amount of 720 rs. So while doing GRN, the accounting document will be as, Material account 36720rs debit and GR/IR account 36720rs credit. While doing invoice, i am changing the

  • Why can't I connect to my Mifi

    I have a Verizon Mifi 4G LTE and I can connect to my Powerbook (which is running on system 10.6.4)  BUT I CAN'T CONNECT TO MY iMAC (which is running on system 10.5.8.  When I try to connect, it "times out".  Any ideas?

  • HT1320 My Ipod classic is frozen with the "do not disconnect" logo on what can I do to un freeze it?

    Hi my ipod classic is frozen with the "Do Not Disconnect" sign on what can I do to unfreeze it ?

  • How to reduce size of generated html page?

    Hi, Is there an option in oc4j which will remove unneeded white space from the html generated by a jsp page? I have jsp page which generates a html page of 120kb (lots of lines containing only spaces). Formatting this html page using tidy results in

  • How can apply Oracle BPEL patch to Oracle BPEL Process manager??

    Hi, Gurus: I am new to Oracle BPEL Process manager, I successfully install Oracle BPEL Process manager, but I need to install Oracle BPEL patch and the examples within it. so I download bpelpatches.zip, it has over 106 MB. It contains: 1. p4369818_10