user1503463
user1503463

Reputation:

How to get the second element alone from a list which contains 2 elements in c#.net?

This is my list definition

public class EventsList
    {
        public int EventID { get; set; }
        public string EventName { get; set; }
    }

This is C# code

string strCurrentUser = CommonWeb.GetLoginUser();
        EventsClass EventObj = new EventsClass();
        DataSet ds;
      List< EventsList> eventList = new List<EventsList>();
       EventsList eventobj = new EventsList();
       ds=EventObj.GetEvents(strCurrentUser);

I have a drop down in which it shoould display the EventName alone. How could i achieve this??

Upvotes: 18

Views: 72141

Answers (4)

Turash
Turash

Reputation: 304

it can be easily achieved using LINQ. Also, we can modify how we want to distinguish the required item.

var Item = oListItem.Select(x=>new Item()).Skip(1).Take(1);

Skip = How many items we want to skip
Take = How many we want to take

Upvotes: 3

kumar
kumar

Reputation: 1

Power of Linq we can achieve this...

Below example I Retrieve the particular Property alone..

List<Item> oListItem = new List<Item>() {
    new Item("CD", "001CD", Enum.GroupTYPE.FAST_MOVING),
    new Item("TV", "002CD", Enum.GroupTYPE.FAST_MOVING),
    new Item("CD", "001CD", Enum.GroupTYPE.FAST_MOVING),
    new Item("LAPTOP", "003CD", Enum.GroupTYPE.FAST_MOVING),
    new Item("MOBILE", "004CD", Enum.GroupTYPE.NORMAL),
    new Item("CHARGER", "005CD", Enum.GroupTYPE.LEAST_MOVING)
};

Retrieve the Name property alone from the Collection

var Item = from Item oname in oListItem select oname.ItemName;

Upvotes: 0

Niladri Biswas
Niladri Biswas

Reputation: 4171

.Select(i => i.Name);

e.g.

static void Main(string[] args)
        {
            var records = GetPersonRecords();

            var onlyName = records.Select(i => i.Name);
        }

        private static List<Person> GetPersonRecords()
        {
            var listPerson = new List<Person>();

            listPerson.Add(new Person { Id = 1, Name = "Name1" });
            listPerson.Add(new Person { Id = 2, Name = "Name2" });

            return listPerson;
        }
    }

    class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

Hope this helps

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1502686

Your question isn't clear, but it sounds like it might be as simple as using the indexer of List<T>, which makes accessing an element look like array access:

List<string> values = ...;
string name = values[1]; // Index is 0-based

For a more general IEnumerable<string> you can use the ElementAt extension method:

using System.Linq;

...
IEnumerable<string> values = ...;
string name = values.ElementAt(1);

Upvotes: 52

Related Questions