Remove Duplicates from dropdown using Linq [duplicate] - c#

This question already has answers here:
Distinct not working with LINQ to Objects [duplicate]
(11 answers)
Closed 7 years ago.
I have a list of books, each book has a author assigned to it.
What I'm trying to do is allow the user the filter the results based on the author.
So some books may have the same Author etc but I want to filter the Authors out only show and entry for each one in my dropdown.
This is what I currently have :
var bookAuthors = Cache.CacheExtension.GetFromCache<List<BookCollection>>("books"); // Returns me the collection of books
// Filter the Authors out of the books
var authorCollection = bookAuthors.DistinctBy(item => new Options { Id = item.BookAuthor.ToString(), Description = item.BookAuthor }).ToList(); // Doesn't remove duplicates
As you can see I'm using DistinctBy but nothing gets filtered.
If I do this
var authorCollection = bookAuthors.Select(item => new Options { Id = item.BookAuthor.ToString(), Description = item.BookAuthor }).ToList(); // I get a list of Authors.
I get the list but it contains duplicates, any help would be grand

Use GroupBy() in Linq
var distinctItems = authorCollection.GroupBy(x => x.Id).Select(y => y.First());

Related

Extracting a list from a list LINQ [duplicate]

This question already has answers here:
Using LINQ, select list of objects inside another list of objects
(2 answers)
Closed 1 year ago.
I am trying to extract a list of Goals from within a list of Students using this method
public List<Goal> GetGoalsForTeacher(int userId)
{
var students = GetStudentsForTeacher(userId);
var result = students.Select(e => e.Goals).ToList();
return result
}
However, I need it to return a List, but it is returning a List<IList>. Has anyone any idea on how I would convert this or make it a List initially?
You're looking for the SelectMany() method.
var result = students.SelectMany(e => e.Goals).ToList();

c# How to save duplicates from list into dictionary? [duplicate]

This question already has answers here:
Using Linq to group a list of objects into a new grouped list of list of objects
(5 answers)
Closed 4 years ago.
I got list of Issues,
Where Issue
public class Issue
{
public string version{ get; set; }
public string someDescription { get; set; }
}
versions are duplicated e.g:
List<
{"1.2.8", value1},
{"1.3.1", value2},
{"1.2.8", value3}
>
and I need to split duplicates into dictionary, where key is a specific verison, and value is a list of values like:
Dictionary<stirng, List<string>> duplicates;
what mean Dictionary<EachVersion, List<valuesForThisVersion>>
got something like this:
var VerisonList = records.GroupBy(r => r.Verison).Select(w=>w.Key).ToList();
this give me a list of versions, but have no idea how to fast get list of values where verison == VerisonList.element;
Is it possible with one linq?
EDIT: This is NOT a duplicate of the other question. In linked post there is no answer for my problem!!
Sure, using ToDictionary():
records.GroupBy(r => r.Verison)
.ToDictionary(g => g.Key,
g => g.Select(i => i.someDescription).ToList());

how can I filter dups from this list? [duplicate]

This question already has answers here:
LINQ's Distinct() on a particular property
(23 answers)
Closed 4 years ago.
I have the following list of objects:
{
DomainName="my-corp-1",
GroupName="group-x",
Desription="my group x"
}
{
DomainName="my-corp-2",
GroupName="group-x",
Desription="my group x - follow up with admin"
}
{
DomainName = "my-corp-1",
GroupName="group-y",
Description="my group y"
}
If an object with the same GroupName exists in both domains then I should keep the object which exists in my-corp-1 and filter out the object with the same GroupName associated with my-corp-2.
For example, in the list of objects above, the second object in the list should be filtered out b/c the GroupName already exists for group-x in the first object.
What would be a clean way to implement this filtering routine in C#?
What's clean tends to be a personal preference :)
I would probably group them by the GroupName, and then act from there. Keeping data until the absolute last step is usually preferable.
// Get an IEnumerable of IGrouping with GroupName as key
var objectsGroupedByGroupName = myDomainList.GroupBy(d => d.GroupName);
// Recklessly throw away data and select only the first object in each grouping per GroupName
var listOfDomainsWithUniqueGroupNames = objectsGroupedByGroupName.Select(x => x.First());
If you just want it more clean, you can of course combine them:
var myUniqueDomainsFromGroupName = myDomainList
.GroupBy(d => d.GroupName) // Group domains by their group name
.Select(x => x.First()) // Select the first entry for each group
//.ToList() if you want a list back
;

Removing items in List using LINQ [duplicate]

This question already has answers here:
Using LINQ to remove elements from a List<T>
(14 answers)
Closed 9 years ago.
I have a List of type some entity
List
public class OrderLine
{
public string productCode;
public int quantity;
}
i need to remove items from the above List if the productCode is equal to some products.
List<string> ProductsToBeExcluded = new List<string>(){"1234","1237"};
so, from List<OrderLine> i need to remove products which are equal to 1234 and 1237
i have tried
create a List<string> from List<OrderLine> using
List<OrderLine> OrderLines = GetOrderLines();
var ol = from o in OrderLines
select o.ProductCode;
2.
List<string> ProductsToBeExcluded = new List<string>(){"1234","1237"};
var filtered = OrderLines.Except(ProductsToBeExcluded);
how do I proceed further in removing
thanks
In this case you don't need LINQ but can just use List<T>.RemoveAll instead
OrderLines.RemoveAll(x => ProductsToBeExcluded.Contains(x.ProductCode));
Use RemoveAll method of List which accepts predicate
OrderLines.RemoveAll(x => ProductsToBeExcluded.Contains(x.ProductCode));

Linq query to dictionary throws System.ArgumentException: An item with the same key has already been added [duplicate]

This question already has answers here:
C# Linq .ToDictionary() Key Already Exists
(3 answers)
Closed 9 years ago.
I have the following LINQ query that I am using to query a datatable and populate a dictionary, but it keeps throwing the error:
System.ArgumentException: An item with the same key has already been
added.
I am new to LINQ and cannot figure out the proper way to write this.
Can someone please assist?
var neworderGroupDict = (from m in KMVData.AsEnumerable()
select new
{
datakey = m.Field<string>("OrderNumber"),
datavalue = m.Field<int>("OrderGroup")
}).Distinct().ToDictionary(n => n.datakey, n => n.datavalue);
That means your data key (in this case combination of OrderNumber and OrderGroup) is not unique. Happens because .Distinct() wont filter duplicates without IEqualityComparer for your type.
Edit:
One way of fixing that and preserving all datavalues for OrderNumber is first grouping by and then converting it to dictionary:
var neworderGroupDict = (from m in KMVData.AsEnumerable()
select new
{
datakey = m.Field<string>("OrderNumber"),
datavalue = m.Field<int>("OrderGroup")
}).GroupBy(x => x.datakey)
.ToDictionary(g => g.Key, g => g.ToList());
Try DistinctBy of MoreLinq.
Then you can use ToDictionary without any problems.

Categories