Reputation: 93036
I have a list of objects FilteredItems
. Each item has a Property NewFileName
. I want now a new list, so that I can act on each object where the NewFileName
is not unique. (I want to change another property of those objects)
I started to write a Linq query, I am able to group them by their NewFileName
, but I am unsure on how to continue now. How can I filter now those where the group count is > 1?
Or am I on the wrong path and there is a completely different solution to get the objects that have not a unique NewFileName
?
var result = from files in FilteredItems
group files by files.newFileName;
foreach (var item in result) {
item.NewFileNameUnique = false;
}
Upvotes: 0
Views: 156
Reputation: 14432
You can also achieve this with a LinQ method chain. Group the list by the 'NewFileName' (GroupBy) and get only those who are not unique (Where) and with the SelectMany you put them in an IEnumerable. Afterwards loop the IEnumerable and set the NewFileNameUnique-property to 'false';
var duplicates = FilteredItems.GroupBy(i => i.NewFileName)
.Where(g => g.Count() > 1)
.SelectMany(r => r.ToList());
foreach(var item in duplicates)
item.NewFileNameUnique = false;
Hope this helps!
Upvotes: 1
Reputation: 22565
Each of your items in your foreach loop is a list of FilteredItem, you should check this list size is bigger than 1 or not, and if is, change all the values in this list:
var result = from files in FilteredItems
group files by files.newFileName;
foreach (var item in result) {
if (item.Count() > 1)
{
foreach(var fileDetail in item)
fileDetail.NewFileNameUnique = false;
}
}
Finally you can set your list by changed value as below:
FilteredItems = result.SelectMany(x=>x).ToList();
Edit: I think should add something here, and that's linq is good for search query's but for updating something is not good, for example you can handle your problem simply with two for loop:
for(int i=0;i<FilteredItems.Count - 1;i++)
for (int j=i+1;j<FilteredItems.Count;j++)
{
if (FilteredItems[i].newFileName == FilteredItems[j].newFileName)
{
FilteredItems[i].NewFileNameUnique = FilteredItems[j].NewFileNameUnique = false;
}
}
Which is more readable, Also you can do it faster by first sorting your list by their newFileName values and then check each item with its next/prev items (in O(n log n)).
Upvotes: 1