如何从包含 c#.net 中的 2 个元素的列表中单独获取第二个元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12153562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the second element alone from a list which contains 2 elements in c#.net?
提问by
This is my list definition
这是我的列表定义
public class EventsList
{
public int EventID { get; set; }
public string EventName { get; set; }
}
This is C# code
这是 C# 代码
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??
我有一个下拉菜单,它应该单独显示 EventName。我怎么能做到这一点?
采纳答案by Jon Skeet
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<T>一样简单,这使得访问元素看起来像数组访问:
List<string> values = ...;
string name = values[1]; // Index is 0-based
For a more general IEnumerable<string>you can use the ElementAtextension method:
对于更一般的,IEnumerable<string>您可以使用ElementAt扩展方法:
using System.Linq;
...
IEnumerable<string> values = ...;
string name = values.ElementAt(1);
回答by Niladri Biswas
.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
希望这可以帮助
回答by kumar
Power of Linqwe can achieve this...
Linq我们的力量可以做到这一点......
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
从集合中单独检索 Name 属性
var Item = from Item oname in oListItem select oname.ItemName;

