Cast Listobject to Listmyclass c#
It seems that you have list of boxed object[]
. So, you need to unbox it and get the values of UserId
, Name
, Address
by its corresponding index.
Here is example:
List<Users> mylist = SelectedList
.Where(item => (int)((object[])item)[0] == 1)
.Select(item =>
{
var values = (object[])item;
return new Users()
{
UserId = (int)values[0],
Name = (string)values[1],
Address = (string)values[2]
};
})
.ToList();
Why can't I cast from a ListMyClass to Listobject?
The reason this is not legal is because it is not safe. Suppose it were legal:
List<Giraffe> giraffes = new List<Giraffe>();
List<Animal> animals = giraffes; // this is not legal; suppose it were.
animals.Add(new Tiger()); // it is always legal to put a tiger in a list of animals
But "animals" is actually a list of giraffes; you can't put a tiger in a list of giraffes.
In C# this is, unfortunately, legal with arrays of reference type:
Giraffe[] giraffes = new Giraffe[10];
Animal[] animals = giraffes; // legal! But dangerous because...
animals[0] = new Tiger(); // ...this fails at runtime!
In C# 4 this is legal on IEnumerable but not IList:
List<Giraffe> giraffes = new List<Giraffe>();
IEnumerable<Animal> animals = giraffes; // Legal in C# 4
foreach(Animal animal in animals) { } // Every giraffe is an animal, so this is safe
It is safe because IEnumerable<T>
does not expose any method that takes in a T.
To solve your problem you can:
- Create a new list of objects out of the old list.
- Make the method take an object[] rather than a
List<object>
, and use unsafe array covariance. - Make the method generic, so it takes a
List<T>
- Make the method take IEnumerable
- Make the method take
IEnumerable<object>
and use C# 4.
Convert ListObject to ListCustomClass
If you know in advance that all of your objects are actually CustomClass
objects, you can perform an unsafe cast:
@SuppressWarnings("unchecked")
List<CustomClass> list = (List<CustomClass>)(List<?>)getObjects();
This is the fastest solution; practically in runtime nothing is performed except the variable assignment. However if you're wrong and your list actually contains other objects, you may have an unexpected ClassCastException
later.
How to convert ListObject into ListT?
You can use a static function similar to:
static <T> List<T> toList(List<Object> object, Class<T> desiredClass) {
List<T> transformedList = new ArrayList<>();
if (object != null) {
for (Object result : object) {
String json = new Gson().toJson(result);
T model = new Gson().fromJson(json, desiredClass);
transformedList.add(model);
}
}
return transformedList;
}
Basically you just need to ensure that you deliver the desired type (e.g. desiredClass
) and use it in fromJson
.
Sample usage:
List<Ticket> ticketList = toList(object, Ticket.class);
List<Price> priceList = toList(object, Price.class);
Note that by moving the object != null
into the toList
-method you do not need to care about what is passed to that method. You at least get an empty list in return.
How to Convert ListString to ListObject
Pass the List<String>
as a parameter to the constructor of a new ArrayList<Object>
.
List<Object> objectList = new ArrayList<Object>(stringList);
Any Collection
can be passed as an argument to the constructor as long as its type extends the type of the ArrayList
, as String
extends Object
. The constructor takes a Collection
, but List
is a subinterface of Collection
, so you can just use the List<String>
.
cast from ListMyClass to ListInterface
Use an upper bound of Interface
for the type: <? extends Interface>
.
Here's come compilable code that uses classes from the JDK to illustrate:
public static void myMethod(List<? extends Comparable> struttura) {}
public static void main(String[] args) {
List<Integer> lista = null;
myMethod(lista); // compiles OK
}
How do you cast a List of supertypes to a List of subtypes?
Simply casting to List<TestB>
almost works; but it doesn't work because you can't cast a generic type of one parameter to another. However, you can cast through an intermediate wildcard type and it will be allowed (since you can cast to and from wildcard types, just with an unchecked warning):
List<TestB> variable = (List<TestB>)(List<?>) collectionOfListA;
Related Topics
Totally Confused with Java.Exe
Spring 3 MVC: One-To-Many Within a Dynamic Form (Add/Remove on Create/Update)
A Rotated Square Panel in Java Gui
Why Does This Subtraction Not Equal Zero
How to Change Background Color of Jtabbedpane
How to Set Base Url for Rest in Spring Boot
Changing Shape of Single Point in Jfreechart Xyplot
How to Loop User Input Until an Integer Is Inputted
Javafx Entirely Customized Windows
How to Redirect to Another Action Class Without Using on Struts.Xml
Java Hashmap Performance Optimization/Alternative
Why Doesn't Java.Lang.Number Implement Comparable
Get Integer Value of the Current Year in Java
What Is the Best Open-Source Java Charting Library? (Other Than Jfreechart)
Spring Security 5:There Is No Passwordencoder Mapped for the Id "Null"