Can this Linq query be entered as nothing but "var"?

When I make a request that returns an anonymous type

    var assets =
        from Product p in Session.CreateLinq<Product>()
        where bundles.Contains(p.ProductBundle)
        select new {p.Asset, p.Asset.PropertyTbl};

Can I print a return to anything other than var?

+3
source share
7 answers

You cannot * return an anonymous type, because the caller does not know which type it cannot use.

If you want to return the results, you can create objects of a non-anonymous type:

IEnumerable<Foo> assets =
    from Product p in Session.CreateLinq<Product>()
    where bundles.Contains(p.ProductBundle)
    select new Foo { Bar = p.Asset, Baz = p.Asset.PropertyTbl};

You can also use the Tuple type in .NET 4 if you do not want to create your own class for your values.


* - , . , .

+6

object dynamic ( .NET 4.0) var, . var , , , , .

+4

:

public class AssetProp
{
   public virtual string Asset {get;set;}
   public virtual string PropertyTbl {get;set;}
}

:

IEnumerable<AssetProp> assets =
    from Product p in Session.CreateLinq<Product>()
    where bundles.Contains(p.ProductBundle)
    select new AssetProp {p.Asset, p.Asset.PropertyTbl};
+1

. , .

var - ? , .

0

, new {p.Asset, p.Asset.PropertyTbl} . object , - , .

0

, -, , .

0

( , "var" , , )

        var element = new { id = 7 };

        List<object> collection = new List<object>();
        element = collection.Select(item => new { id = 0 }).First();
0

Source: https://habr.com/ru/post/1756704/


All Articles