Você está na página 1de 3

MENU

ProudMonkey
VaoriuWsaytoGsD
entsVictaulerofsmaLst<iT>
unsiLN
gIQ
02 JUNE 2015 on ASP.NET, WEB DEVELOPMENT, WebForms, LINQ

This article talks about the various scenarios regarding ltering distinct values from the
List. One practical example is if you have a list of products and wanted to get the distinct
values from the list. To make it more clear lets take an example. Consider that we have
this model below that houses the following properties:

public class Product


{
public int ProductID { get; set; }
public string Make { get; set; }
public string Model { get; set; }
}

Now lets create a method that would create a list of Products. For example:

private List<Product> GetProducts() {


List<Product> products = new List<Product>();
products.Add(new Product { ProductID = 1, Make = "Samsung", Model = "Gal
axy S3" });
products.Add(new Product { ProductID = 2, Make = "Samsung", Model = "Gal
axy S4" });
products.Add(new Product { ProductID = 3, Make = "Samsung", Model = "Gal
axy S5" });
products.Add(new Product { ProductID = 4, Make = "Apple", Model = "iPhon
e 5" });
products.Add(new Product { ProductID = 5, Make = "Apple", Model = "iPhon
e 6" });
products.Add(new Product { ProductID = 6, Make = "Apple", Model = "iPhon
e 6" });
products.Add(new Product { ProductID = 7, Make = "HTC", Model = "Sensati
on" });
products.Add(new Product { ProductID = 8, Make = "HTC", Model = "Desire"
});
products.Add(new Product { ProductID = 9, Make = "HTC", Model = "Desire"
});
products.Add(new Product { ProductID = 10, Make = "Nokia", Model = "Lumi
a 735" });
products.Add(new Product { ProductID = 11, Make = "Nokia", Model = "Lumi
a 930" });
products.Add(new Product { ProductID = 12, Make = "Nokia", Model = "Lumi
a 930" });
products.Add(new Product { ProductID = 13, Make = "Sony", Model = "Xperi
a Z3" });

return products;
}

The method above returns a list of Products by adding a dummy data to the List just for
the simplicity of this demo. In a real scenario you may want to query your database and
load the result to your model. Now lets bind the Products data in GridView.

protected void Page_Load(object sender, EventArgs e) {


if (!IsPostBack) {
GridView1.DataSource = GetProducts();
GridView1.DataBind();
}
}

Running the code will give you the following output below:

If you noticed there are few items above that contain the same values or commonly
called "duplicate" values. Now lets try to get the distinct row values from the list using
the LINQ Distinct function. The code now would look like this:

if (!IsPostBack) {
GridView1.DataSource = GetProducts().Distinct();
GridView1.DataBind();
}

Unfortunately, running the code will still give you the same output. This means that the
Distinct LINQ function doesnt work at all. I was surprised and my rst reaction was like
Only 2 pages have been converted.
Please go to https://docs.zone and Sign Up to convert all pages.

Você também pode gostar