Is there a way to specify an anonymous empty enumerated type?

I am returning an anonymous Json'ed type:

IList<MyClass> listOfStuff = GetListOfStuff();

return Json(
   new {
       stuff = listOfStuff
   }
);

In some cases, I know what listOfStuffwill be empty. Therefore, I do not want the overhead of the call GetListOfStuff()(which causes the database call).

So in this case, I write:

return Json(
   new {
       stuff = new List<ListOfStuff>()
   }
);

which seems a bit overly detailed. I don’t care what type Listhe is, because he is still empty.

Is there a shorthand notation that can be used to denote an empty enumerated / list / array? Sort of:

return Json(
   new {
       stuff = new []
   }
);

Or have I been programming JavaScript for too long? :)

+5
source share
6 answers

. # , . , . :

return Json(
   new {
       stuff = new ListOfStuff[]{}
   }
);

, [] JSON. , . , , , .

+5

?:

List<Object>()

: new Object[0]

+2

, , . # , , ( , ), . , new ListOfStuff[0], . ( ) ( , , IList<T>).

+2

Enumerable.Empty, :

return Json(
    new {
        stuff = Enumerable.Empty<ListOfStuff>()
    }
);

.

+1

Yes there is. You must define an array with at least one element and use linq to filter an array that does not leave any elements. Example:

var foo = new
{
    Code = 1,
    Name = "Bar",
    Value = (float?)5.0
};

//use an empty object (or any object) to define the type of the array
var emptyArrayOfFooType = new[] {
    new
    {
        Code = (int)0,
        Name = (string)null,
        Value = (float?)null
    }
}.Where(e => false).ToArray(); //use linq to filter the array leaving no elements

//you can use an existing anonymous type variable too
var anotherEmptyArray = new[] { foo }.Where(e => false).ToArray();

//this array with one element has the same type of the previous two arrays
var fooArray = new[] { foo };

//all arrays have the same type, so you can combine them
var combinedArrays = emptyArrayOfFooType.Concat(anotherEmptyArray).Union(fooArray);
0
source

I think you are talking about C # here. My knowledge is limited in C #, but I don't think you can create a new object without a type. Why can't you return a generic new list []? (maybe Java generators are mixed here, I'm not sure if you can return a generic list of types in C #).

-3
source

All Articles