Json Array - retrieve first record in C# - c#

I am obtaining a JSON array in a dynamic object.
How can I obtain the first item( equivalent of First for List collection)?
How can I check if Json array is empty

If that's all you want to do with it, and if the underlying object implements IEnumerable, you could use:
foreach (dynamic item in array)
{
// Use it here
break;
}
Or use First explicitly:
dynamic first = Enumerable.First(array);

Related

Map JsonObject to class json

I m trying to populate class object from excel.I received values in json which i m deserializing but i dont want to get List
because in handler class there is function that is of type policy how i can map PolicyNew to class object without List.
var json = JsonConvert.SerializeObject(query);
var policynew = JsonConvert.DeserializeObject<List<PolicyNew>>(json);
Policy policy = Handler.GeneratePolicy(policynew);
//Handler.cs
Handler.GeneratePolicy(PolicyNew policynew)
{
}
If your jsonstring contains an array, you have to deserialize to some sort of List/Array. If you know, you will only need a single element of that list (or you know, that list only contains one element) you can just take the first element of the resulting list.
var policynew = JsonConvert.DeserializeObject<List<PolicyNew>>(json).FirstOrDefault();
If you have control over the generation of the json string, you could change the serialization and not create an array [{"p1": 3, ...}] but a single object {"p1": 3, ...}

How to convert the return item into list from array in C#

I want to convert the output in the list as the method calls in the webservice returns item in the list and here it is returning in the array.
catalogueItems = dataService.GetCatalogItemsFromFile(fileFullPath);
I need to convert this dataService.GetCatalogItemsFromFile(fileFullPath) into a list. How should I do this ?
There are many ways, this one is without knowing the type:
var list = new[] { dataService.GetCatalogItemsFromFile(fileFullPath) }.ToList()
If you know the type this is better:
var list = new List<YourType>{ dataService.GetCatalogItemsFromFile(fileFullPath) };

How to access a list with an index from a calling function

I am writing a c# console program.
I have a function that returns a list of objects.
e.g the following will return a list of objects.
p.getList();
If I already know the index of the object I want to reference from the list, then how to I access this?
For example I want to do the following which obviously is incorrect:
p.getList()[Index]
This would give me the item in the list at index.
To get around this I have done the following:
List<MyObject> mylist = p.getList();
mylist[Index];
but the above seems inefficient, to have to create a copy just to reference a value.
Any tips on how I can access?
Thanks.
If you don't want the list, but an item and you know the Index then
var item = p.getList()[Index];
syntax is perfectly correct. Please, notice, that List<T> is a reference type, that's why in case of
var list = p.getList(); // reference copy, not the collection cloning
var item = list[Index];
...
var otherItem = list[otherIndex];
the var list = p.getList(); adds a miniscule overhead: it's reference, not the entire collection is being copied.

get specific value from ArrayList in C#

I am using ArrayList in Asp.net I want to extract specific items . My code is
ArrayList items = (ArrayList)Session["mycart"];
foreach(var v in items)
{
}
but this is not working . I want to get value like
v.myvalue;
My arralist is filled with several items coming from prevoius page.
The issue is that ArrayList stores all elements as object. You need to perform a cast to the type of object that contains myvalue.
For example
ArrayList items = (ArrayList)Session["mycart"];
foreach(var v in items)
{
MyObject o = v as MyObject;
if (o != null)
{
// do stuff with o.myvalue
}
}
It may be better to just use the generic List class rather ArrayList, although you may have a perfectly reason for doing otherwise. Generally, you should use the generic (e.g. List<MyObject>), not only for performance but also ease of use.

How to remove items in IEnumerable<MyClass>?

How do I remove items from a IEnumerable that match specific criteria?
RemoveAll() does not apply.
You can't; IEnumerable as an interface does not support removal.
If your IEnumerable instance is actually of a type that supports removal (such as List<T>) then you can cast to that type and use the Remove method.
Alternatively you can copy items to a different IEnumerable based on your criteria, or you can use a lazy-evaluated query (such as with Linq's .Where) to filter your IEnumerable on the fly. Neither of these will affect your original container, though.
This will produce a new collection rather than modifying the existing one however I think it is the idiomatic way to do it with LINQ.
var filtered = myCollection.Where(x => x.SomeProp != SomValue);
Another option would be to use Where to produce a new IEnumerable<T> with references to the objects you want removed then pass that to a Remove call on the original collection. Of course that would actually consume more resources.
You can't remove items from an IEnumerable<T>. You can remove items from an ICollection<T> or filter items from an IEnumerable<T>.
// filtering example; does not modify oldEnumerable itself
var filteredEnumerable = oldEnumerable.Where(...);
// removing example
var coll = (ICollection<MyClass>)oldEnumerable;
coll.Remove(item);
You don't remove items from an IEnumerable. It's not possible. It's just a sequence of items. You can remove items from some underlying source that generates the sequences, for example if the IEnumerable is based on a list you can remove items from that list.
The other option you have is to create a new sequence, based on this one, that never shows the given items. You can do that using Where, but it's important to realize this isn't removing items, but rather choosing to show items based on a certain condition.
As everyone has already stated, you can't remove from IEnumerable because that is not what the interface is describing. Consider the following example:
public IEnumerable<string> GetSomeStrings()
{
yield return "FirstString";
yield return "Another string";
}
Clearly, removing an element from this IEnumerable is not something you can reasonably do, instead you'd have to make a new enumeration without the ones you don't want.
The yield keywork provides other examples, for example, you can have infinite lists:
public IEnumberable<int> GetPowersOf2()
{
int value = 1;
while(true)
{
yield return value;
value = value * 2;
}
}
Items cannot be removed from an IEnumerable<T>. From the documentation:
Exposes the enumerator, which supports a simple iteration over a collection of a specified type.
You can cast it and use the List<T>.RemoveAll(Predicate<T> match) this is exactly what you need.
This is how i do,
IEnumerable<T> myVar=getSomeData(); // Assume mayVar holds some data
myVar=myVar.Where(d=>d.Id>10); // thats all, i want data with Id>10 only
How about trying Enumerable.Empty i.e.
T obj = new T();
IEnumerable<T> myVar = new T[]{obj} //Now myVar has an element
myVar = Enumerable.Empty<T>(); //Now myVar is empty

Categories

Resources