Get distinct list values

2020-02-11 02:05发布

i have a C# application in which i'd like to get from a List of Project objects , another List which contains distinct objects.

i tried this

 List<Project> model = notre_admin.Get_List_Project_By_Expert(u.Id_user);
 if (model != null) model = model.Distinct().ToList();

The list model still contains 4 identical objects Project.

What is the reason of this? How can i fix it?

8条回答
Animai°情兽
2楼-- · 2020-02-11 02:40
List<ViewClReceive> passData = (List<ViewClReceive>)TempData["passData_Select_BankName_List"];
    passData = passData?.DistinctBy(b=>b.BankNm).ToList();

It will Works ......

查看更多
放荡不羁爱自由
3楼-- · 2020-02-11 02:41

Check this example: you need to use either Comparator or override Equals()

class Program
{
    static void Main( string[] args )
    {
        List<Item> items = new List<Item>();
        items.Add( new Item( "A" ) );
        items.Add( new Item( "A" ) );
        items.Add( new Item( "B" ) );
        items.Add( new Item( "C" ) );

        items = items.Distinct().ToList();
    }
}

public class Item
{
    string Name { get; set; }
    public Item( string name )
    {
        Name = name;
    }

    public override bool Equals( object obj )
    {
        return Name.Equals((obj as Item).Name);
    }
    public override int GetHashCode()
    {
        return Name.GetHashCode();
    }
}
查看更多
登录 后发表回答