I've an IEnumerable list named list. It keeps these sample values:
I want to access and assign to any variables these Count, Start and End values, whenever I want. How can I do this?
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.
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.
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
Try:
list.Count()
list.First() or list.FirstOrDefault()
list.Last() or list.LastOrDefault()
Related
I have a list:
List<string> theList = new List<string>;
There are a few elements in the List. And now I want to get an item by the index. e.g. I want to get element number 4. How can I do it?
Just use the indexer
string item = theList[3];
Note that indexes in C# are 0 based. So if you want the 4th element in the list you need to use index 3. If you want the 5th element you would use index 4. It's unclear from your question which you intended
The indexer is a common feature on .Net collection types. For lists it's generally index based, for maps it's key based. The documentation for the type in question will tell you which and if it's available. The indexer member will be listed though as the property named Item
http://msdn.microsoft.com/en-us/library/0ebtbkkc.aspx
To get 4th item, you can use indexer:
string item = theList[3];
if you prefer to use methods, then you can use ElementAt or (ElementAtOrDefault):
string item = theList.ElementAt(3);
You can use the Indexer to get the Item at selected index
string item = theList[3];
Use the indexer:
string the4th = theList[3];
Note that this throws an exception if the list has only 3 items or less since the index is always zero-based. You might want to use Enumerable.ElementAtOrDefault then:
string the4th = theList.ElementAtOrDefault(3);
if(the4th != null)
{
// ...
}
ElementAtOrDefault returns the element at the specified index if index < list.Count and default(T) if index >= theList.Count. So for reference types(like String) it returns null and for value types their default value(e.g. 0 for int).
For collection types which implement IList<T>(arrays or lists) it uses the indexer to get the element, for other types it uses a foreach loop and a counter variable.
So you could also use the Count property to check if the list contains enough items for the index:
string the4th = null;
if(index < theList.Count)
{
the4th = theList[index];
}
use the Indexer Syntax:
var fourthItem = theList[3];
this should do it, access via array index.
theList[3]
its 3 as index's start at 0.
You can use the Indexer to get the Item at selected index
string item = theList[3];
Or if u want to get the id (if accessing from database) define a class e.g.
public class Person
{
public int PId;
public string PName;
}
and access as follow
List<Person> theList = new List<Person>();
Person p1 = new Person();
int id = theList[3].PId
I have such code:
List<Vector3> list = fillTheList();
How can I get element from it on specyfied position?
You can get it by using its indexer.
var item = list[index];
Lists also have indexers like arrays do.
For example if you want to have the second item in the list you would write:
var vectorFromList = list[1]
List has an indexer that accepts integer, the index of the element in the List
ls[0] // gets the first element
ls[1] // gets the second element
i just linq to find the max object from a list of object now i want change it back from var to object. How is that done.
List < MyObject> lt = matchings.ToList();
var wwe = lt.Max(ya => ya.Similarity);
var itemsMax = lt.Where(xa => xa.Similarity == wwe);
MyObject sm =(TemplateMatch) itemsMax;//it gives error here
var is not a type. It's a keyword meaning "fill in the type for me".
Where returns a collection. You are attempting to cast a collection to a single item.
Instead of Where, use FirstOrDefault.
var itemsMax = lt.FirstOrDefault(xa => xa.Similarity == wwe);
Now you get back a single item, and can cast it if needed.
Note the above works if you only want a single item with that value.
If it is possible to have multiple items with the max value--and you want multiple items back--combine Where with OfType or Cast.
var itemsMax = lt.Where(xa => xa.Similarity == wwe);
var allItemsCasted = itemsMax.Cast<NewType>(); // this throws
var typeCompatibleItems = itemsMax.OfType<NewType>(); // this filters
The problem seems to be that Where returns a collection of objects, but you need only a single object. Try itemsMax.Single()
Instead of enumerating through the matchings twice (once to calculate the "max similarity" and a second time to find the item that has the max similarity), you could do this in one pass using IEnumerable<T>.Aggregate:
var sm = matchings.Aggregate((maxItem, next) =>
next.Similarity > maxItem.Similarity ? next : maxItem);
Your lt.Where returns an enumerable. So, that's why it does not cast to a single object. Add a .Single() method on the end and it should cast.
i have a list contains set of strings, i want to fetch the data present in the list based on index, with out using iterator.. is there any functions like get() or getat() some sort of method using which we can fetch?
myList[index] is the way to go
List<string> myList = new List<string>();
myList.Add("string 1");
myList.Add("String 2");
Console.WriteLine(myList[0]); // string 1
Console.WriteLine(myList[1]); // String 2
List<string> myList = new List<string();
//add some elements to the list
//then get the third element
string thirdElement = myList[2];
You can just do:
item = list[i];
Use the overloaded index operator.
List<String> list; // ... initialize, populate list
String element = list[1]; // get the element at index 1
If your collection implements IList<T>, just use indexer. Otherwise, if your collection only allows forward-only access (that is, only implements IEnumerable<T>) you can use ElementAt() method, but it still uses iterator under the hood.
I don't know what kind of list you're talking about exactly, but most collections in .net have a CopyTo function, and you can access individual items with the [] operator.
List<string> list = new List<string>();
list.Add("lots of strings");
//If you want to print all the strings you can do:
foreach(string str in list)
Console.WriteLine(str);
//If you want to modify each string in the list, make each lower case for example,
// you can do. this is working by using the index of the elements in the list:
for(int i = 0; i < list.Count; i++)
list[i] = list[i].ToLower();
If you use the generic type List (or another implementation of IList) you can use the index operator to directly access items at certain positions: item = myList[3]
If you use a type that only implements IEnumerable you should use the ElementAt() function.
What's your reason to avoid the use of iterators?
C# Array, How to make data in an array distinct from each other?
For example
string[] a = {"a","b","a","c","b","b","c","a"};
how to get
string[]b = {"a","b","c"}
Easiest way is the LINQ Distinct() command :
var b = a.Distinct().ToArray();
You might want to consider using a Set instead of an array. Sets can't contain duplicates so adding the second "a" would have no effect. That way your collection of characters will always contain no duplicates and you won't have to do any post processing on it.
var list = new HashSet<string> { };
list.Add("a");
list.Add("a");
var countItems = list.Count(); //in this case countItems=1
An array, which you start with, is IEnumerable<T>. IEnumerable<T> has a Distinct() method which can be used to manipulate the list into its distinct values
var distinctList = list.Distinct();
Finally,IEnumerable<T> has a ToArray() method:
var b = distinctList.ToArray();
I think using c# Dictionary is the better way and I can sort by value using LINQ