Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I populate a list of my own class directly in LINQ?

Tags:

c#

linq

This is the example:

public class FotoLiveLove
{
    public string Tipologia { get; set; }
    public string URL { get; set; }
}

IList<FotoLiveLove> fotoLiveLove = xDoc["statuses"].Select(x => new
{
    Tipologia = "twitter",
    URL = (string)x["URLJSON"]
}).ToList();    

but it says acnnot convert Anonymous type #1 to FotoLiveLove.

like image 498
markzzz Avatar asked Jul 16 '13 12:07

markzzz


People also ask

What will convert a collection into an array in LINQ?

ToArray() operator in LINQ is used to convert the input elements in the collection to an Array.

How do I return a single value from a list using LINQ?

var fruit = ListOfFruits. FirstOrDefault(x => x.Name == "Apple"); if (fruit != null) { return fruit.ID; } return 0; This is not the only road to Rome, you can also use Single(), SingleOrDefault() or First().

What is any () in LINQ?

The Any operator is used to check whether any element in the sequence or collection satisfy the given condition. If one or more element satisfies the given condition, then it will return true. If any element does not satisfy the given condition, then it will return false.

Does LINQ select return new object?

While the LINQ methods always return a new collection, they don't create a new set of objects: Both the input collection (customers, in my example) and the output collection (validCustomers, in my previous example) are just sets of pointers to the same objects.


3 Answers

You need to add your class name after the new keyword:

IList<FotoLiveLove> fotoLiveLove = xDoc["statuses"].Select(x => new FotoLiveLove()
{
    Tipologia = "twitter",
    URL = (string)x["URLJSON"]
}).ToList();  
like image 180
CodingIntrigue Avatar answered Sep 20 '22 15:09

CodingIntrigue


You have to specify the type on the .Select. Try something like:

IList<FotoLiveLove> fotoLiveLove = xDoc["statuses"].Select(x => new FotoLiveLove() 
{
    Tipologia = "twitter",
    URL = (string)x["URLJSON"]
}).ToList();  
like image 36
Felipe Oriani Avatar answered Sep 23 '22 15:09

Felipe Oriani


I prefer using the query form in these cases (but that's just a preference):

IList<FotoLiveLove> fotoLiveLove = (from f in x.Doc["statuses"]
                               select new FotoLiveLove(){
                                   Tipologia = "twitter",
                                   URL = (string)x["URLJSON"]
                               }).ToList();
like image 39
Mister Epic Avatar answered Sep 21 '22 15:09

Mister Epic