Distinct in Linq based on only one field of the table
Try this:
table1.GroupBy(x => x.Text).Select(x => x.FirstOrDefault());
This will group the table by Text
and use the first row from each groups resulting in rows where Text
is distinct.
Select All distinct values in a column using LINQ
To have unique Categories:
var uniqueCategories = repository.GetAllProducts()
.Select(p => p.Category)
.Distinct();
How to use Distinct in entity/linq based on certain columns (Remove duplicated values)
You can't apply distinct to a subset of properties and still keep the rest of the properties because distinct "groups" values. Other properties that are not included in the distinct result cannot be part of the result because they might have multiple, different values (like your Distance example).
As HoneyBadger suggested, you can simulate a distinct with a GroupBy()
, then select all the .Key
properties and compute aggregate functions on the rest of the properties:
var listdata = (from c in _context.OpenLabelTag select c)
.Select(x => new { x.LabelName, x.OpenLabelStandard, x.Type, Distance = x.Coordinates.Distance(searchArea), x.Coordinates })
.Where(x => x.Coordinates.IsWithinDistance(searchArea, InputRadius) && x.OpenLabelStandard != null)
.GroupBy(x => new { x.LabelName, x.OpenLabelStandard, x.Type })
.Select(gr => new
{
gr.Key.LabelName,
gr.Key.OpenLabelStandard,
gr.Key.Type,
MinDistance = gr.Min(x => x.Distance)
})
.OrderBy(s => s.MinDistance)
.Take(10).ToList();
Note that I removed the Distinct()
and also moved the OrderBy()
to after the grouping operation.
Linq Distinct on specific field
You could write an IEqualityComparer
that compares the ID
values and pass it into the overloaded Queryable.Distinct method, but since this is LINQ to SQL it won't be supported on the database. You would have to add a call to the AsEnumerable
method to get it working, but this isn't recommended for large amounts of data because you would be bringing the data down to the client side. If you decide to go that route you will end up with a query similar to:
var query = dc.Operators.AsEnumerable().Distinct(new OperatorEqualityComparer());
The other option, which makes the database do the work, is to group by ID
and take the first item in each group:
var query = from p in dc.Operators
group p by p.ID into groups
select groups.First();
Get full rows based on single column distinct
You can use GroupBy
var data = DB.tblDocumentTypes.GroupBy(m => m.Doc_Type).Select(x => x.First());
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
.
LINQ query to return distinct field values from list of objects
objList.Select(o=>o.typeId).Distinct()
How to return or display distinct values only from a specific column using EF Core?
For those who are looking the same output result as this scenario. I just missed the filter condition inside my for loop. Here's my updated code which resolve my previous issue.
Code
string curItem1 = null;
string curItem2 = null;
using (var context = new SchoolsContext(options))
{
var teachingPersonnel = new List<TeachingViewModel>();
var teachingPersonnel2 = context.TeachingPersonnel.AsNoTracking().Where(x => x.School_Id == School_Id)
.Select(x => new TeachingViewModel
{
Id = x.Id,
School_Id = x.School_Id,
OrderId = x.OrderId,
Grade_Level = x.Grade_Level,
Name = x.Name,
Position = x.Position,
}).OrderBy(x => x.OrderId).ToList();
for (int item = 0; item < teachingPersonnel2.Count(); item++)
{
curItem1 = teachingPersonnel2[item].Grade_Level;
if (curItem1 != curItem2)
{
curItem2 = teachingPersonnel2[item].Grade_Level;
teachingPersonnel.Add(new TeachingViewModel
{
Id = teachingPersonnel2[item].Id,
School_Id = teachingPersonnel2[item].School_Id,
OrderId = teachingPersonnel2[item].OrderId,
Grade_Level = teachingPersonnel2[item].Grade_Level,
Name = teachingPersonnel2[item].Name,
Position = teachingPersonnel2[item].Position,
});
}
else
{
teachingPersonnel.Add(new TeachingViewModel
{
Id = teachingPersonnel2[item].Id,
School_Id = teachingPersonnel2[item].School_Id,
OrderId = teachingPersonnel2[item].OrderId,
Grade_Level = string.Empty,
Name = teachingPersonnel2[item].Name,
Position = teachingPersonnel2[item].Position,
});
}
}
return teachingPersonnel;
}
}
Distinct in LINQ-C#
The 3 records that you see at debug time is your existing list. I think all that you've missed is an assignment.
List<LinqTest> myList = new List<LinqTest>();
myList.Add(new LinqTest() { id = 1, value = "a" });
myList.Add(new LinqTest() { id = 1, value = "b" });
myList.Add(new LinqTest() { id = 2, value = "c" });
// not sure why new {m.id} was used in this context
List<int> distinctList = myList.Select(m => m.id).Distinct().ToList();
Related Topics
Programmatically Get a Screenshot of a Page
How to Find Fqdn of Local MAChine in C#/.Net
Convert String to Hex-String in C#
Linq Where List Contains Any in List
Virtual Webcam Input as Byte Stream
How to Execute a Command in a Remote Computer
Synchronized Scrolling of Two Scrollviewers Whenever Any One Is Scrolled in Wpf
Convert Binary String into Integer
What Is the JSON.Net Equivalent of Xml's Xpath, Selectnodes, Selectsinglenode
What's the Correct Alternative to Static Method Inheritance
Getting the "Diff" Between Two Arrays in C#
How to Read a Text File Without Locking It
Should I Use Two "Where" Clauses or "&&" in My Linq Query