Reputation: 105
In my controller i am returning list of my object with specific property:
public ActionResult Index()
{
List<MyObject> list = db.MyObjects.Where(x => x.family == "Web").ToList();
ViewBag.Files = new SelectList(list, "Id", "protocol");
return View();
}
This is my object:
public class MyObject
{
public int id { get; set; }
public string fileName { get; set; }
public string browser { get; set; }
public string protocol { get; set; }
public string family { get; set; }
}
Index.cshtml:
@Html.DropDownList("File", new SelectList(ViewBag.Files, "Id", "protocol_site"), "Select webmail site", new { style = "vertical-align:middle;" })
And i try to made 2 changes with no succeed:
Remove all the duplication protocol from my DropDownList
for exapmle if i have 10 objects : 9 is doc protocol and 1 pdf i wand to see in my DropDownList
only 2 items: DOC and PDF and not all the 10 items.
Sort this DropDownList
in alphabet order
Upvotes: 0
Views: 146
Reputation: 4464
As @Dreamcatcher mentioned in his answer, you should pass already prepared collection to SelectList
constructor and use linq for these tasks. For Distinct
linq method you will need to create custom comparer, which will compare objects by protocol field:
public sealed class MyObjectByProtocolComparer: IEqualityComparer<MyObject>
{
public bool Equals(MyObject x, MyObject y)
{
return x.protocol.Equals(y.protocol);
}
public int GetHashCode(MyObject obj)
{
return obj.protocol.GetHashCode();
}
}
This is rather simple implementation, you might need to check for null values. After that use it in your linq query:
var list = db.MyObjects.Where(x => x.family == "Web").ToArray();
list = list.Distinct(new MyObjectByProtocolComparer())
.OrderBy(x => x.fileName)
.ToArray();
Upvotes: 1
Reputation: 444
Follow the guidelines in this page http://msdn.microsoft.com/en-us/library/ms173147(v=vs.80).aspx so that you can call linq Distinct
Upvotes: 0
Reputation: 828
You should add second line in your code. However i am not sure correct spelling, i did not use VS. Also if Disctinct does not work correctly, you should write Comparer.
List<MyObject> list = db.MyObjects.Where(x => x.family == "Web").ToList();
list= list.OrderBy(x => x.fileName).Distinct().ToList();
Upvotes: 1