How to use LINQ Distinct() with multiple fields
I assume that you use distinct like a method call on a list. You need to use the result of the query as datasource for your DropDownList, for example by materializing it via ToList
.
var distinctCategories = product
.Select(m => new {m.CategoryId, m.CategoryName})
.Distinct()
.ToList();
DropDownList1.DataSource = distinctCategories;
DropDownList1.DataTextField = "CategoryName";
DropDownList1.DataValueField = "CategoryId";
Another way if you need the real objects instead of the anonymous type with only few properties is to use GroupBy
with an anonymous type:
List<Product> distinctProductList = product
.GroupBy(m => new {m.CategoryId, m.CategoryName})
.Select(group => group.First()) // instead of First you can also apply your logic here what you want to take, for example an OrderBy
.ToList();
A third option is to use MoreLinq's DistinctBy
.
Distinct on multiple fields
Try with
GroupBy(
p => new {p.ItemName, p.SubItemName}
).Select(g => new { g.Key.ItemName, g.Key.SubItemName });
How to LINQ Distinct by Multiple Fields without anonymous types
You can do the following:
return
from c in AllClasses
group c by new
{
c.Batch,
c.Degree_ID,
c.Specialization_ID,
c.CurrentSemester,
c.Section_ID
} into grp
select grp.First();
This takes every first Class
from the given group, thus returns a Entity object instead of a anonymous type.
How to select distinct based on combination of two fields with LINQ?
You can select just the name and age into an anonymous type, and then use Distinct()
:
var results = context.people
.Select(p => new { p.Name, p.Age })
.Distinct();
Obviously that won't give you the height, but then there is no single height. If you want all the heights as well, you need to group instead:
var results = context.people
.GroupBy(p => new { p.Name, p.Age });
That will give you a sequence of groupings, where each grouping contains all the people with the same name and age.
LINQ, how to select distinct with two columns
As far as I can understand you want to distinct records by subfield
. If so, you can do that using GroupBy
:
var pList = db.Part.Where(p => p.field != null && p.field!= "")
.OrderByDescending(l => l.ID)
.AsEnumerable()
.GroupBy(x => x.subfield)
.Select(x => x.First())
.Select(x => new SelectListItem
{
Value = x.ID.ToString(),
Text = x.subfield
});
Or if you can use a third party library I recommend DistinctBy
method
var pList = db.Part.Where(p => p.field != null && p.field!= "")
.OrderByDescending(l => l.ID)
.AsEnumerable()
.DistinctBy(x => x.subfield)
.Select(x => new SelectListItem
{
Value = x.ID.ToString(),
Text = x.subfield
});
I optimized your code a bit by changing ToArray
with AsEnumerable
, if you just want to fetch result you can use AsEnumerable
, it will execute the query and enumerate the results, you don't need to put the result into a collection.
Select distinct list from nested collections on multiple fields
Try This Group by with multiple Keys.
List<Instrument> ins = clientAcccounts.SelectMany(x => x.Holdings.Select(s => s.Instrument)).ToList().GroupBy(p=> new {p.InstrumentID,p.AssetTypeID},(key,group)=>group.First()).ToList<Instrument>();
Distinct on Multiple Columns Entity Framework LINQ
Using anonymous objects will do the trick:
var data = TESTDB.Where(i => i.ALPHA == 1).Select(i => new {i.A, i.B, i.C}).Distinct();
To retain the model:
List<Book> books = db.Book.Select(i => new Book {Author = i.Author, Title = i.Title}).Distinct().ToList();
LINQ to DataSet, distinct by multiple columns
Well, you can do the projection first:
var qry = db.Customers.Select(cust => new {cust.ID, cust.Name, cust.Region})
.Distinct();
Or in query syntax:
var qry = (from cust in db.Customers
select new {cust.ID, cust.Name, cust.Region}).Distinct();
That do?
LINQ to SQL select distinct from multiple colums
The trouble you're having is that VB.NET treats the objects returned from a Linq query differently than C# does, which is why a lot of the answers here are from baffled C# developers. VB.NET returns mutable objects from Linq queries. C# returns immutable objects. So, in C# equality is already handled for you, but in VB.NET you have to specify which fields are considered equal using the Key
keyword. You can see this easily in LinqPad yourself:
Dim items As New List(Of KeyValuePair(Of Integer, String))()
items.Add(New KeyValuePair(Of Integer, String)(1, "David"))
items.Add(New KeyValuePair(Of Integer, String)(2, "James"))
items.Add(New KeyValuePair(Of Integer, String)(3, "Smith"))
items.Add(New KeyValuePair(Of Integer, String)(2, "James"))
items.Add(New KeyValuePair(Of Integer, String)(5, "Joe"))
items.Dump()
Dim uhOhResult = (from a in items select New With {a.Key, a.Value}).Distinct()
usOhResult.Dump()
Dim distinctResult = (from a in items select New With {Key a.Key, Key a.Value}).Distinct()
distinctResult.Dump()
In your example, put the Key
keyword in to define which fields participate in the equality check, and distinct will work properly.
Dim customer = (From cus In db.Customers Select Key cus.CustomerId, Key cus.CustomerName).Distinct()
See here: Linq Group on Multiple Fields - VB.NET, Anonymous, Key
and here: Distinct in LINQ with anonymous types (in VB.NET)
Related Topics
MVC Validation Lower/Higher Than Other Value
External Handler for Msiexec Msisetexternalui
The Difference Between Virtual, Override, New and Sealed Override
What Makes a Method Thread-Safe? What Are the Rules
Split a String That Has White Spaces, Unless They Are Enclosed Within "Quotes"
How to Convert a System.Io.Stream to a Windows.Storage.Streams.Irandomaccessstream
How to Get the Last Four Characters from a String in C#
.Net Configuration (App.Config/Web.Config/Settings.Settings)
How to Find the Current Executable Filename
Contextswitchdeadlock Was Detected Error in C#
How to Make Backgroundworker Return an Object
How to Omit Methods from Swagger Documentation on Webapi Using Swashbuckle
.Net Core 3 Yields Different Floating Point Results from Version 2.2
Using a Pagedlist with a Viewmodel ASP.NET MVC
How to Convert a File into Byte Array in Memory
Factory Pattern in C#: How to Ensure an Object Instance Can Only Be Created by a Factory Class