使用foreach从List过滤对象

时间:2011-08-18 09:45:15

标签: c# linq list delegates

您好我有一个对象列表,但如何将其过滤到另一个列表?

例如:

public class Person
{
    public string FirstName;
    public string Language;

    public Person (string FirstName, string Language)
    {
        this.FirstName = FirstName;
        this.LastName = Language;            
    }
 }

创建一个列表:

public List<Person> createDummyList()
{
  List<Person> dummyList = new List<Person>();
  dummyList.Add(new Person("Per", "English"));
  dummyList.Add(new Person("Linda", "Spanish"));
}

如何使用该语言获取一个List,然后将其绑定到一个下拉列表。?我试过这样的东西,但得到了一个空引用...

public void filterList(List<Person> ListToBeFiltered)
{
    List<string> LanguageList = new List<string>();
    ListToBeFiltered.ForEach(delegate(Person P) 
    {
       LanguageList.Add(P.Language);
    });
    DropDown.datasource = LanguageList;
    DropDown.databind();
 }

任何人都可以指出我正确的方向吗?

2 个答案:

答案 0 :(得分:4)

IEnumerable<string> languageList = listToBeFiltered.Select(p=>p.Language)
                                                   .Distinct()
                                                   .ToList();

答案 1 :(得分:0)

public void filterList(List<Person> ListToBeFiltered)
{
        DropDown.datasource = ListToBeFiltered.Select(p=>p.Language).Distinct();
        DropDown.databind();
}