Select distinct using linq
myList.GroupBy(test => test.id)
.Select(grp => grp.First());
Edit: as getting this IEnumerable<>
into a List<>
seems to be a mystery to many people, you can simply write:
var result = myList.GroupBy(test => test.id)
.Select(grp => grp.First())
.ToList();
But one is often better off working with the IEnumerable
rather than IList
as the Linq above is lazily evaluated: it doesn't actually do all of the work until the enumerable is iterated. When you call ToList
it actually walks the entire enumerable forcing all of the work to be done up front. (And may take a little while if your enumerable is infinitely long.)
The flipside to this advice is that each time you enumerate such an IEnumerable
the work to evaluate it has to be done afresh. So you need to decide for each case whether it is better to work with the lazily evaluated IEnumerable
or to realize it into a List
, Set
, Dictionary
or whatnot.
Select All distinct values in a column using LINQ
To have unique Categories:
var uniqueCategories = repository.GetAllProducts()
.Select(p => p.Category)
.Distinct();
LINQ Equivalent of SELECT DISTINCT
All the provided answers are applicable only if you have moreLINQ. However, you can try this instead:
this.Distinct_CourseNo = (from c in Roster_Sections
group c by c.CourseNo into g
select g.First()).ToList();
LINQ's Distinct() on a particular property
EDIT: This is now part of MoreLINQ.
What you need is a "distinct-by" effectively. I don't believe it's part of LINQ as it stands, although it's fairly easy to write:
public static IEnumerable<TSource> DistinctBy<TSource, TKey>
(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
HashSet<TKey> seenKeys = new HashSet<TKey>();
foreach (TSource element in source)
{
if (seenKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
So to find the distinct values using just the Id
property, you could use:
var query = people.DistinctBy(p => p.Id);
And to use multiple properties, you can use anonymous types, which implement equality appropriately:
var query = people.DistinctBy(p => new { p.Id, p.Name });
Untested, but it should work (and it now at least compiles).
It assumes the default comparer for the keys though - if you want to pass in an equality comparer, just pass it on to the HashSet
constructor.
Select distinct column name from db using LINQ
Either declare your method to return an IE of string:
public IEnumerable<string> GetAllMakes()
And your query to not make an anonymous type but simply select the make:
return context.EbimaCarMakesAndModels.Select(l => l.CarMake).Distinct().ToList();
Or group by make and return some nominal entry from the group list (but that doesn’t really make sense to me)
return context.EbimaCarMakesAndModels.GroupBy(x => x.CarMake)
.Select(x => x.FirstOrDefault()).ToList();
Your last query introduced some additional unmentioned constraint .Where(v => v.Listed == "Y")
- perhaps consider doing this on EbimaCarMakesAndModels
before you group
Select distinct values from a list using LINQ in C#
You could implement a custom IEqualityComparer<Employee>
:
public class Employee
{
public string empName { get; set; }
public string empID { get; set; }
public string empLoc { get; set; }
public string empPL { get; set; }
public string empShift { get; set; }
public class Comparer : IEqualityComparer<Employee>
{
public bool Equals(Employee x, Employee y)
{
return x.empLoc == y.empLoc
&& x.empPL == y.empPL
&& x.empShift == y.empShift;
}
public int GetHashCode(Employee obj)
{
unchecked // overflow is fine
{
int hash = 17;
hash = hash * 23 + (obj.empLoc ?? "").GetHashCode();
hash = hash * 23 + (obj.empPL ?? "").GetHashCode();
hash = hash * 23 + (obj.empShift ?? "").GetHashCode();
return hash;
}
}
}
}
Now you can use this overload of Enumerable.Distinct
:
var distinct = employees.Distinct(new Employee.Comparer());
The less reusable, robust and efficient approach, using an anonymous type:
var distinctKeys = employees.Select(e => new { e.empLoc, e.empPL, e.empShift })
.Distinct();
var joined = from e in employees
join d in distinctKeys
on new { e.empLoc, e.empPL, e.empShift } equals d
select e;
// if you want to replace the original collection
employees = joined.ToList();
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();
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.
LINQ query to return distinct field values from list of objects
objList.Select(o=>o.typeId).Distinct()
Related Topics
What Does Synchronizationcontext Do
Specified Argument Was Out of the Range of Valid Values. Parameter Name: Site
Is There a Faster Way to Scan Through a Directory Recursively in .Net
Opening a Folder in Explorer and Selecting a File
Prevent Property from Being Serialized in Web API
How to Get First Record in Each Group Using Linq
Debugging Automatic Properties
Dependent Dll Is Not Getting Copied to the Build Output Folder in Visual Studio
Injecting Dependencies into ASP.NET MVC 3 Action Filters. What's Wrong with This Approach
How to Convert an Object to a Byte Array in C#
Linq to SQL: Multiple Joins on Multiple Columns. Is This Possible
Sending Email with Attachments from C#, Attachments Arrive as Part 1.2 in Thunderbird
C# - Code to Order by a Property Using the Property Name as a String
Best Way to Invoke Any Cross-Threaded Code