1teamsah
1teamsah

Reputation: 1933

How to get IEnumerable list values?

I've an IEnumerable list named list. It keeps these sample values:

enter image description here

I want to access and assign to any variables these Count, Start and End values, whenever I want. How can I do this?

Upvotes: 5

Views: 72772

Answers (4)

WhileTrueSleep
WhileTrueSleep

Reputation: 1534

It's possible to access the list with Linq using the namespace

using System.Linq;

like so

var firstListElement = list.ElementAt(0);
var firstListElementCount = firstListElement.Count;
// do more stuff with my first element of the list

Upvotes: 2

David
David

Reputation: 219097

The IEnumerable itself doesn't have Count, Start, or End. It's elements do, so you'll need to identify the element in the collection from which you want to read those values. For example, to read the values on the first element:

var firstCount = list.First().Count;
var firstStart = list.First().Start;
var firstEnd = list.First().End;

Or if you want to get a collection of all the Count values, something like this:

var allCounts = list.Select(c => c.Count);

You're operating on a collection of elements, not a single element. So to get information from any particular element you first need to identify it from the collection. And there are lots of methods you can chain together to identify any given element or set of elements.

Upvotes: 12

Ron
Ron

Reputation: 6755

Try:

list.Count()
list.First() or list.FirstOrDefault()
list.Last() or list.LastOrDefault()

Upvotes: -1

Selman Genç
Selman Genç

Reputation: 101732

Use a loop ?

foreach(var item in list)
{
   var count = item.Count;
}

Or use ToList and convert it to List<T> then you can access your value with index:

var myList = list.ToList();
var count = myList[0].Count;

Also if you know the type you can cast your IEnumerable to IList<T> in order to use indexer.

Upvotes: 5

Related Questions