WPF C# How can I filter a ObservableCollection or QueryableCollectionView
WPF C# How can I filter a ObservableCollection or QueryableCollectionView?
I want to filter and list all categories which has the same duplicated Category Code.
Like code: Test123 consists of these categories. In other word, the categorycode should be unique.
I tried this with QueryableCollectionView:
var test = CategoryCollection.GroupBy(Category => Category.Code).Where(w => w.Count() > 1);
But it didn't work.
My code sample:
public ObservableCollection<Category> GetCategory
{
get
{
this._getCategory = GetCategory();
this._getCategory.GroupBy(category => category.Code).ToList().Where(w => w.Count() > 1); ;
this._getCategory = new ObservableCollection<Category>(_getCategory);
return this._getCategory.
}
set
{
if (this._getCategory != value)
{
this._getCategory = value;
this.OnPropertyChanged("GetCategory");
}
}
}
c# wpf
|
show 1 more comment
WPF C# How can I filter a ObservableCollection or QueryableCollectionView?
I want to filter and list all categories which has the same duplicated Category Code.
Like code: Test123 consists of these categories. In other word, the categorycode should be unique.
I tried this with QueryableCollectionView:
var test = CategoryCollection.GroupBy(Category => Category.Code).Where(w => w.Count() > 1);
But it didn't work.
My code sample:
public ObservableCollection<Category> GetCategory
{
get
{
this._getCategory = GetCategory();
this._getCategory.GroupBy(category => category.Code).ToList().Where(w => w.Count() > 1); ;
this._getCategory = new ObservableCollection<Category>(_getCategory);
return this._getCategory.
}
set
{
if (this._getCategory != value)
{
this._getCategory = value;
this.OnPropertyChanged("GetCategory");
}
}
}
c# wpf
You need an ICollectionView as shown here: wpftutorial.net/dataviews.html You can then get away with using a List instead of an ObservableCollection if you wish.
– Coops
Nov 20 '18 at 14:02
Does changes etc to the collection or the data also apply to this collection?
– user6870932
Nov 20 '18 at 14:04
If you were to use a List as the base property then I would say no, so in that case you can use an ObservableCollection as it would suit your needs. But whenever you change the filtering or something else you need to call .Refresh() on your ICollectionView
– Coops
Nov 20 '18 at 14:09
Hi, I'm not going to change the filter. I just want to list all the categories that is duplicated by checking if a code exist more than one time. I would like to use obseravblecollection for this, if it's possible to filter.
– user6870932
Nov 20 '18 at 14:13
It sounds very much like you're trying to do a couple of things with this collection. Are you trying to keep a collection with unique categories? If so then in your logic to add items you need to check for duplicates or even use a different type of collection, a dictionary for example. Also view which categories are duplicate, for what reason? If you can give a more complete explanation we can help more.
– Coops
Nov 20 '18 at 14:19
|
show 1 more comment
WPF C# How can I filter a ObservableCollection or QueryableCollectionView?
I want to filter and list all categories which has the same duplicated Category Code.
Like code: Test123 consists of these categories. In other word, the categorycode should be unique.
I tried this with QueryableCollectionView:
var test = CategoryCollection.GroupBy(Category => Category.Code).Where(w => w.Count() > 1);
But it didn't work.
My code sample:
public ObservableCollection<Category> GetCategory
{
get
{
this._getCategory = GetCategory();
this._getCategory.GroupBy(category => category.Code).ToList().Where(w => w.Count() > 1); ;
this._getCategory = new ObservableCollection<Category>(_getCategory);
return this._getCategory.
}
set
{
if (this._getCategory != value)
{
this._getCategory = value;
this.OnPropertyChanged("GetCategory");
}
}
}
c# wpf
WPF C# How can I filter a ObservableCollection or QueryableCollectionView?
I want to filter and list all categories which has the same duplicated Category Code.
Like code: Test123 consists of these categories. In other word, the categorycode should be unique.
I tried this with QueryableCollectionView:
var test = CategoryCollection.GroupBy(Category => Category.Code).Where(w => w.Count() > 1);
But it didn't work.
My code sample:
public ObservableCollection<Category> GetCategory
{
get
{
this._getCategory = GetCategory();
this._getCategory.GroupBy(category => category.Code).ToList().Where(w => w.Count() > 1); ;
this._getCategory = new ObservableCollection<Category>(_getCategory);
return this._getCategory.
}
set
{
if (this._getCategory != value)
{
this._getCategory = value;
this.OnPropertyChanged("GetCategory");
}
}
}
c# wpf
c# wpf
edited Nov 21 '18 at 15:28
asked Nov 20 '18 at 13:53
user6870932
You need an ICollectionView as shown here: wpftutorial.net/dataviews.html You can then get away with using a List instead of an ObservableCollection if you wish.
– Coops
Nov 20 '18 at 14:02
Does changes etc to the collection or the data also apply to this collection?
– user6870932
Nov 20 '18 at 14:04
If you were to use a List as the base property then I would say no, so in that case you can use an ObservableCollection as it would suit your needs. But whenever you change the filtering or something else you need to call .Refresh() on your ICollectionView
– Coops
Nov 20 '18 at 14:09
Hi, I'm not going to change the filter. I just want to list all the categories that is duplicated by checking if a code exist more than one time. I would like to use obseravblecollection for this, if it's possible to filter.
– user6870932
Nov 20 '18 at 14:13
It sounds very much like you're trying to do a couple of things with this collection. Are you trying to keep a collection with unique categories? If so then in your logic to add items you need to check for duplicates or even use a different type of collection, a dictionary for example. Also view which categories are duplicate, for what reason? If you can give a more complete explanation we can help more.
– Coops
Nov 20 '18 at 14:19
|
show 1 more comment
You need an ICollectionView as shown here: wpftutorial.net/dataviews.html You can then get away with using a List instead of an ObservableCollection if you wish.
– Coops
Nov 20 '18 at 14:02
Does changes etc to the collection or the data also apply to this collection?
– user6870932
Nov 20 '18 at 14:04
If you were to use a List as the base property then I would say no, so in that case you can use an ObservableCollection as it would suit your needs. But whenever you change the filtering or something else you need to call .Refresh() on your ICollectionView
– Coops
Nov 20 '18 at 14:09
Hi, I'm not going to change the filter. I just want to list all the categories that is duplicated by checking if a code exist more than one time. I would like to use obseravblecollection for this, if it's possible to filter.
– user6870932
Nov 20 '18 at 14:13
It sounds very much like you're trying to do a couple of things with this collection. Are you trying to keep a collection with unique categories? If so then in your logic to add items you need to check for duplicates or even use a different type of collection, a dictionary for example. Also view which categories are duplicate, for what reason? If you can give a more complete explanation we can help more.
– Coops
Nov 20 '18 at 14:19
You need an ICollectionView as shown here: wpftutorial.net/dataviews.html You can then get away with using a List instead of an ObservableCollection if you wish.
– Coops
Nov 20 '18 at 14:02
You need an ICollectionView as shown here: wpftutorial.net/dataviews.html You can then get away with using a List instead of an ObservableCollection if you wish.
– Coops
Nov 20 '18 at 14:02
Does changes etc to the collection or the data also apply to this collection?
– user6870932
Nov 20 '18 at 14:04
Does changes etc to the collection or the data also apply to this collection?
– user6870932
Nov 20 '18 at 14:04
If you were to use a List as the base property then I would say no, so in that case you can use an ObservableCollection as it would suit your needs. But whenever you change the filtering or something else you need to call .Refresh() on your ICollectionView
– Coops
Nov 20 '18 at 14:09
If you were to use a List as the base property then I would say no, so in that case you can use an ObservableCollection as it would suit your needs. But whenever you change the filtering or something else you need to call .Refresh() on your ICollectionView
– Coops
Nov 20 '18 at 14:09
Hi, I'm not going to change the filter. I just want to list all the categories that is duplicated by checking if a code exist more than one time. I would like to use obseravblecollection for this, if it's possible to filter.
– user6870932
Nov 20 '18 at 14:13
Hi, I'm not going to change the filter. I just want to list all the categories that is duplicated by checking if a code exist more than one time. I would like to use obseravblecollection for this, if it's possible to filter.
– user6870932
Nov 20 '18 at 14:13
It sounds very much like you're trying to do a couple of things with this collection. Are you trying to keep a collection with unique categories? If so then in your logic to add items you need to check for duplicates or even use a different type of collection, a dictionary for example. Also view which categories are duplicate, for what reason? If you can give a more complete explanation we can help more.
– Coops
Nov 20 '18 at 14:19
It sounds very much like you're trying to do a couple of things with this collection. Are you trying to keep a collection with unique categories? If so then in your logic to add items you need to check for duplicates or even use a different type of collection, a dictionary for example. Also view which categories are duplicate, for what reason? If you can give a more complete explanation we can help more.
– Coops
Nov 20 '18 at 14:19
|
show 1 more comment
3 Answers
3
active
oldest
votes
I've made a code sample that works as you've described now, see below:
MainWindow.xaml
<Window x:Class="TestWpfApplication.MainWindowView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="MainWindow"
Height="450"
Width="800">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<ListBox Grid.Row="0" Grid.Column="0" Name="CategoryListBox" ItemsSource="{Binding Path=CategoryCollection}" DisplayMemberPath="Description" />
<TextBox Grid.Row="0" Grid.Column="1" Text="{Binding ElementName=CategoryListBox, Path=SelectedItem.Code}" />
</Grid>
MainWindow.xaml.cs
using System.Windows;
namespace TestWpfApplication
{
public partial class MainWindowView : Window
{
private readonly MainWindowViewModel _mainWindowViewModel = new MainWindowViewModel();
public MainWindowView()
{
InitializeComponent();
DataContext = _mainWindowViewModel;
}
}
}
MainWindowViewModel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows.Data;
namespace TestWpfApplication
{
internal class MainWindowViewModel
{
private readonly List<Category> _categories;
public MainWindowViewModel()
{
_categories = new List<Category>
{
new Category {Code = 1, Description = "Blah"},
new Category {Code = 1, Description = "Blah"},
new Category {Code = 2, Description = "Pop"},
new Category {Code = 3, Description = "No"},
new Category {Code = 3, Description = "No"},
new Category {Code = 4, Description = "Yes"}
};
HookUpCategoryEvents();
CategoryCollection = CollectionViewSource.GetDefaultView(_categories);
CategoryCollection.Filter = OnlyShowIfMoreThanOne;
}
private bool OnlyShowIfMoreThanOne(object obj)
{
Category item = obj as Category;
return _categories.Count(c => c.Code == item.Code) > 1;
}
public ICollectionView CategoryCollection { get; }
private void HookUpCategoryEvents()
{
// If you add items or remove them at any point then you need to call this method
// It removes the event so you don't get existing items being 'hooked up' double or more times
foreach (var category in _categories)
{
category.CodeChanged -= CategoryOnCodeChanged;
category.CodeChanged += CategoryOnCodeChanged;
}
}
private void CategoryOnCodeChanged(object sender, EventArgs e)
{
CategoryCollection.Refresh();
}
}
}
Category.cs
using System;
namespace TestWpfApplication
{
public class Category
{
private int _code;
private string _description;
public event EventHandler CodeChanged;
public int Code
{
get => _code;
set
{
if (_code != value)
{
_code = value;
OnCodeChanged();
}
}
}
public string Description
{
get => _description;
set => _description = value;
}
private void OnCodeChanged()
{
CodeChanged?.Invoke(this, EventArgs.Empty);
}
}
}
This displays a simple ListBox that is set to show the Description property of the Category class and a TextBox that shows the SelectedItem.Code of the ListBox.
In the ViewModel the ICollectionView has a filter applied to it so that it only shows items those codes appear more than once. An event is fired from the Category class upon setting the Code property (from the TextBox) which the MainWindowViewModel listens to and uses to call .Refresh() on the ICollectionView. There is no validation or other things that you'd want in production code but this should show you the basics of what you're wanting.
Your example is really nice, my only problem is that I use ObservableCollection and Queryablecollection for most of my stuff to hold my categories, and most of the application is done that way. Is it possible to apply a QueryCollectionView into Icollectionview with filter?
– user6870932
Nov 21 '18 at 14:46
You can use ObservableCollection instead of List but as far as a QueryableCollectionView, this is something I've not heard of and looks from a quick Google to be a Telerik thing. Just give things a try and see what you come out with.
– Coops
Nov 21 '18 at 14:54
I've updated the code in the topic. Could you see what I'm doing wrong?
– user6870932
Nov 21 '18 at 15:30
Use an ICollectionView instead of an ObservableCollection property, whatever you have in the View will bind to it.
– Coops
Nov 21 '18 at 15:32
Let's say if I have a ICollectionView instead of that ObservableCollection, how would the code be? I guess I can just make do: private ICollectionView test = new ICollectionView(ObservableCollection)?
– user6870932
Nov 21 '18 at 16:06
|
show 4 more comments
var test = CategoryCollection.GroupBy(Category => Category.Code).toList().Where(w => w.Count() > 1);
Can I use a observable collection?
– user6870932
Nov 20 '18 at 14:32
add a comment |
List<Category> listResult= yourObservableCollection.GroupBy(c => c.Code)
.Select(cl=>new Caegory
{
Code=cl.First().Code;
// other parameters of Category here
}).ToList().Where(w=>w.Count()>1);
ObservableCollection<Category> result=new ObservableCollection<Category>(listResult);
I don't know about QueryableCollectionView, but for ObservableCollection it works
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53394545%2fwpf-c-sharp-how-can-i-filter-a-observablecollection-or-queryablecollectionview%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
I've made a code sample that works as you've described now, see below:
MainWindow.xaml
<Window x:Class="TestWpfApplication.MainWindowView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="MainWindow"
Height="450"
Width="800">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<ListBox Grid.Row="0" Grid.Column="0" Name="CategoryListBox" ItemsSource="{Binding Path=CategoryCollection}" DisplayMemberPath="Description" />
<TextBox Grid.Row="0" Grid.Column="1" Text="{Binding ElementName=CategoryListBox, Path=SelectedItem.Code}" />
</Grid>
MainWindow.xaml.cs
using System.Windows;
namespace TestWpfApplication
{
public partial class MainWindowView : Window
{
private readonly MainWindowViewModel _mainWindowViewModel = new MainWindowViewModel();
public MainWindowView()
{
InitializeComponent();
DataContext = _mainWindowViewModel;
}
}
}
MainWindowViewModel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows.Data;
namespace TestWpfApplication
{
internal class MainWindowViewModel
{
private readonly List<Category> _categories;
public MainWindowViewModel()
{
_categories = new List<Category>
{
new Category {Code = 1, Description = "Blah"},
new Category {Code = 1, Description = "Blah"},
new Category {Code = 2, Description = "Pop"},
new Category {Code = 3, Description = "No"},
new Category {Code = 3, Description = "No"},
new Category {Code = 4, Description = "Yes"}
};
HookUpCategoryEvents();
CategoryCollection = CollectionViewSource.GetDefaultView(_categories);
CategoryCollection.Filter = OnlyShowIfMoreThanOne;
}
private bool OnlyShowIfMoreThanOne(object obj)
{
Category item = obj as Category;
return _categories.Count(c => c.Code == item.Code) > 1;
}
public ICollectionView CategoryCollection { get; }
private void HookUpCategoryEvents()
{
// If you add items or remove them at any point then you need to call this method
// It removes the event so you don't get existing items being 'hooked up' double or more times
foreach (var category in _categories)
{
category.CodeChanged -= CategoryOnCodeChanged;
category.CodeChanged += CategoryOnCodeChanged;
}
}
private void CategoryOnCodeChanged(object sender, EventArgs e)
{
CategoryCollection.Refresh();
}
}
}
Category.cs
using System;
namespace TestWpfApplication
{
public class Category
{
private int _code;
private string _description;
public event EventHandler CodeChanged;
public int Code
{
get => _code;
set
{
if (_code != value)
{
_code = value;
OnCodeChanged();
}
}
}
public string Description
{
get => _description;
set => _description = value;
}
private void OnCodeChanged()
{
CodeChanged?.Invoke(this, EventArgs.Empty);
}
}
}
This displays a simple ListBox that is set to show the Description property of the Category class and a TextBox that shows the SelectedItem.Code of the ListBox.
In the ViewModel the ICollectionView has a filter applied to it so that it only shows items those codes appear more than once. An event is fired from the Category class upon setting the Code property (from the TextBox) which the MainWindowViewModel listens to and uses to call .Refresh() on the ICollectionView. There is no validation or other things that you'd want in production code but this should show you the basics of what you're wanting.
Your example is really nice, my only problem is that I use ObservableCollection and Queryablecollection for most of my stuff to hold my categories, and most of the application is done that way. Is it possible to apply a QueryCollectionView into Icollectionview with filter?
– user6870932
Nov 21 '18 at 14:46
You can use ObservableCollection instead of List but as far as a QueryableCollectionView, this is something I've not heard of and looks from a quick Google to be a Telerik thing. Just give things a try and see what you come out with.
– Coops
Nov 21 '18 at 14:54
I've updated the code in the topic. Could you see what I'm doing wrong?
– user6870932
Nov 21 '18 at 15:30
Use an ICollectionView instead of an ObservableCollection property, whatever you have in the View will bind to it.
– Coops
Nov 21 '18 at 15:32
Let's say if I have a ICollectionView instead of that ObservableCollection, how would the code be? I guess I can just make do: private ICollectionView test = new ICollectionView(ObservableCollection)?
– user6870932
Nov 21 '18 at 16:06
|
show 4 more comments
I've made a code sample that works as you've described now, see below:
MainWindow.xaml
<Window x:Class="TestWpfApplication.MainWindowView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="MainWindow"
Height="450"
Width="800">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<ListBox Grid.Row="0" Grid.Column="0" Name="CategoryListBox" ItemsSource="{Binding Path=CategoryCollection}" DisplayMemberPath="Description" />
<TextBox Grid.Row="0" Grid.Column="1" Text="{Binding ElementName=CategoryListBox, Path=SelectedItem.Code}" />
</Grid>
MainWindow.xaml.cs
using System.Windows;
namespace TestWpfApplication
{
public partial class MainWindowView : Window
{
private readonly MainWindowViewModel _mainWindowViewModel = new MainWindowViewModel();
public MainWindowView()
{
InitializeComponent();
DataContext = _mainWindowViewModel;
}
}
}
MainWindowViewModel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows.Data;
namespace TestWpfApplication
{
internal class MainWindowViewModel
{
private readonly List<Category> _categories;
public MainWindowViewModel()
{
_categories = new List<Category>
{
new Category {Code = 1, Description = "Blah"},
new Category {Code = 1, Description = "Blah"},
new Category {Code = 2, Description = "Pop"},
new Category {Code = 3, Description = "No"},
new Category {Code = 3, Description = "No"},
new Category {Code = 4, Description = "Yes"}
};
HookUpCategoryEvents();
CategoryCollection = CollectionViewSource.GetDefaultView(_categories);
CategoryCollection.Filter = OnlyShowIfMoreThanOne;
}
private bool OnlyShowIfMoreThanOne(object obj)
{
Category item = obj as Category;
return _categories.Count(c => c.Code == item.Code) > 1;
}
public ICollectionView CategoryCollection { get; }
private void HookUpCategoryEvents()
{
// If you add items or remove them at any point then you need to call this method
// It removes the event so you don't get existing items being 'hooked up' double or more times
foreach (var category in _categories)
{
category.CodeChanged -= CategoryOnCodeChanged;
category.CodeChanged += CategoryOnCodeChanged;
}
}
private void CategoryOnCodeChanged(object sender, EventArgs e)
{
CategoryCollection.Refresh();
}
}
}
Category.cs
using System;
namespace TestWpfApplication
{
public class Category
{
private int _code;
private string _description;
public event EventHandler CodeChanged;
public int Code
{
get => _code;
set
{
if (_code != value)
{
_code = value;
OnCodeChanged();
}
}
}
public string Description
{
get => _description;
set => _description = value;
}
private void OnCodeChanged()
{
CodeChanged?.Invoke(this, EventArgs.Empty);
}
}
}
This displays a simple ListBox that is set to show the Description property of the Category class and a TextBox that shows the SelectedItem.Code of the ListBox.
In the ViewModel the ICollectionView has a filter applied to it so that it only shows items those codes appear more than once. An event is fired from the Category class upon setting the Code property (from the TextBox) which the MainWindowViewModel listens to and uses to call .Refresh() on the ICollectionView. There is no validation or other things that you'd want in production code but this should show you the basics of what you're wanting.
Your example is really nice, my only problem is that I use ObservableCollection and Queryablecollection for most of my stuff to hold my categories, and most of the application is done that way. Is it possible to apply a QueryCollectionView into Icollectionview with filter?
– user6870932
Nov 21 '18 at 14:46
You can use ObservableCollection instead of List but as far as a QueryableCollectionView, this is something I've not heard of and looks from a quick Google to be a Telerik thing. Just give things a try and see what you come out with.
– Coops
Nov 21 '18 at 14:54
I've updated the code in the topic. Could you see what I'm doing wrong?
– user6870932
Nov 21 '18 at 15:30
Use an ICollectionView instead of an ObservableCollection property, whatever you have in the View will bind to it.
– Coops
Nov 21 '18 at 15:32
Let's say if I have a ICollectionView instead of that ObservableCollection, how would the code be? I guess I can just make do: private ICollectionView test = new ICollectionView(ObservableCollection)?
– user6870932
Nov 21 '18 at 16:06
|
show 4 more comments
I've made a code sample that works as you've described now, see below:
MainWindow.xaml
<Window x:Class="TestWpfApplication.MainWindowView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="MainWindow"
Height="450"
Width="800">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<ListBox Grid.Row="0" Grid.Column="0" Name="CategoryListBox" ItemsSource="{Binding Path=CategoryCollection}" DisplayMemberPath="Description" />
<TextBox Grid.Row="0" Grid.Column="1" Text="{Binding ElementName=CategoryListBox, Path=SelectedItem.Code}" />
</Grid>
MainWindow.xaml.cs
using System.Windows;
namespace TestWpfApplication
{
public partial class MainWindowView : Window
{
private readonly MainWindowViewModel _mainWindowViewModel = new MainWindowViewModel();
public MainWindowView()
{
InitializeComponent();
DataContext = _mainWindowViewModel;
}
}
}
MainWindowViewModel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows.Data;
namespace TestWpfApplication
{
internal class MainWindowViewModel
{
private readonly List<Category> _categories;
public MainWindowViewModel()
{
_categories = new List<Category>
{
new Category {Code = 1, Description = "Blah"},
new Category {Code = 1, Description = "Blah"},
new Category {Code = 2, Description = "Pop"},
new Category {Code = 3, Description = "No"},
new Category {Code = 3, Description = "No"},
new Category {Code = 4, Description = "Yes"}
};
HookUpCategoryEvents();
CategoryCollection = CollectionViewSource.GetDefaultView(_categories);
CategoryCollection.Filter = OnlyShowIfMoreThanOne;
}
private bool OnlyShowIfMoreThanOne(object obj)
{
Category item = obj as Category;
return _categories.Count(c => c.Code == item.Code) > 1;
}
public ICollectionView CategoryCollection { get; }
private void HookUpCategoryEvents()
{
// If you add items or remove them at any point then you need to call this method
// It removes the event so you don't get existing items being 'hooked up' double or more times
foreach (var category in _categories)
{
category.CodeChanged -= CategoryOnCodeChanged;
category.CodeChanged += CategoryOnCodeChanged;
}
}
private void CategoryOnCodeChanged(object sender, EventArgs e)
{
CategoryCollection.Refresh();
}
}
}
Category.cs
using System;
namespace TestWpfApplication
{
public class Category
{
private int _code;
private string _description;
public event EventHandler CodeChanged;
public int Code
{
get => _code;
set
{
if (_code != value)
{
_code = value;
OnCodeChanged();
}
}
}
public string Description
{
get => _description;
set => _description = value;
}
private void OnCodeChanged()
{
CodeChanged?.Invoke(this, EventArgs.Empty);
}
}
}
This displays a simple ListBox that is set to show the Description property of the Category class and a TextBox that shows the SelectedItem.Code of the ListBox.
In the ViewModel the ICollectionView has a filter applied to it so that it only shows items those codes appear more than once. An event is fired from the Category class upon setting the Code property (from the TextBox) which the MainWindowViewModel listens to and uses to call .Refresh() on the ICollectionView. There is no validation or other things that you'd want in production code but this should show you the basics of what you're wanting.
I've made a code sample that works as you've described now, see below:
MainWindow.xaml
<Window x:Class="TestWpfApplication.MainWindowView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="MainWindow"
Height="450"
Width="800">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<ListBox Grid.Row="0" Grid.Column="0" Name="CategoryListBox" ItemsSource="{Binding Path=CategoryCollection}" DisplayMemberPath="Description" />
<TextBox Grid.Row="0" Grid.Column="1" Text="{Binding ElementName=CategoryListBox, Path=SelectedItem.Code}" />
</Grid>
MainWindow.xaml.cs
using System.Windows;
namespace TestWpfApplication
{
public partial class MainWindowView : Window
{
private readonly MainWindowViewModel _mainWindowViewModel = new MainWindowViewModel();
public MainWindowView()
{
InitializeComponent();
DataContext = _mainWindowViewModel;
}
}
}
MainWindowViewModel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows.Data;
namespace TestWpfApplication
{
internal class MainWindowViewModel
{
private readonly List<Category> _categories;
public MainWindowViewModel()
{
_categories = new List<Category>
{
new Category {Code = 1, Description = "Blah"},
new Category {Code = 1, Description = "Blah"},
new Category {Code = 2, Description = "Pop"},
new Category {Code = 3, Description = "No"},
new Category {Code = 3, Description = "No"},
new Category {Code = 4, Description = "Yes"}
};
HookUpCategoryEvents();
CategoryCollection = CollectionViewSource.GetDefaultView(_categories);
CategoryCollection.Filter = OnlyShowIfMoreThanOne;
}
private bool OnlyShowIfMoreThanOne(object obj)
{
Category item = obj as Category;
return _categories.Count(c => c.Code == item.Code) > 1;
}
public ICollectionView CategoryCollection { get; }
private void HookUpCategoryEvents()
{
// If you add items or remove them at any point then you need to call this method
// It removes the event so you don't get existing items being 'hooked up' double or more times
foreach (var category in _categories)
{
category.CodeChanged -= CategoryOnCodeChanged;
category.CodeChanged += CategoryOnCodeChanged;
}
}
private void CategoryOnCodeChanged(object sender, EventArgs e)
{
CategoryCollection.Refresh();
}
}
}
Category.cs
using System;
namespace TestWpfApplication
{
public class Category
{
private int _code;
private string _description;
public event EventHandler CodeChanged;
public int Code
{
get => _code;
set
{
if (_code != value)
{
_code = value;
OnCodeChanged();
}
}
}
public string Description
{
get => _description;
set => _description = value;
}
private void OnCodeChanged()
{
CodeChanged?.Invoke(this, EventArgs.Empty);
}
}
}
This displays a simple ListBox that is set to show the Description property of the Category class and a TextBox that shows the SelectedItem.Code of the ListBox.
In the ViewModel the ICollectionView has a filter applied to it so that it only shows items those codes appear more than once. An event is fired from the Category class upon setting the Code property (from the TextBox) which the MainWindowViewModel listens to and uses to call .Refresh() on the ICollectionView. There is no validation or other things that you'd want in production code but this should show you the basics of what you're wanting.
answered Nov 21 '18 at 9:04
CoopsCoops
1666
1666
Your example is really nice, my only problem is that I use ObservableCollection and Queryablecollection for most of my stuff to hold my categories, and most of the application is done that way. Is it possible to apply a QueryCollectionView into Icollectionview with filter?
– user6870932
Nov 21 '18 at 14:46
You can use ObservableCollection instead of List but as far as a QueryableCollectionView, this is something I've not heard of and looks from a quick Google to be a Telerik thing. Just give things a try and see what you come out with.
– Coops
Nov 21 '18 at 14:54
I've updated the code in the topic. Could you see what I'm doing wrong?
– user6870932
Nov 21 '18 at 15:30
Use an ICollectionView instead of an ObservableCollection property, whatever you have in the View will bind to it.
– Coops
Nov 21 '18 at 15:32
Let's say if I have a ICollectionView instead of that ObservableCollection, how would the code be? I guess I can just make do: private ICollectionView test = new ICollectionView(ObservableCollection)?
– user6870932
Nov 21 '18 at 16:06
|
show 4 more comments
Your example is really nice, my only problem is that I use ObservableCollection and Queryablecollection for most of my stuff to hold my categories, and most of the application is done that way. Is it possible to apply a QueryCollectionView into Icollectionview with filter?
– user6870932
Nov 21 '18 at 14:46
You can use ObservableCollection instead of List but as far as a QueryableCollectionView, this is something I've not heard of and looks from a quick Google to be a Telerik thing. Just give things a try and see what you come out with.
– Coops
Nov 21 '18 at 14:54
I've updated the code in the topic. Could you see what I'm doing wrong?
– user6870932
Nov 21 '18 at 15:30
Use an ICollectionView instead of an ObservableCollection property, whatever you have in the View will bind to it.
– Coops
Nov 21 '18 at 15:32
Let's say if I have a ICollectionView instead of that ObservableCollection, how would the code be? I guess I can just make do: private ICollectionView test = new ICollectionView(ObservableCollection)?
– user6870932
Nov 21 '18 at 16:06
Your example is really nice, my only problem is that I use ObservableCollection and Queryablecollection for most of my stuff to hold my categories, and most of the application is done that way. Is it possible to apply a QueryCollectionView into Icollectionview with filter?
– user6870932
Nov 21 '18 at 14:46
Your example is really nice, my only problem is that I use ObservableCollection and Queryablecollection for most of my stuff to hold my categories, and most of the application is done that way. Is it possible to apply a QueryCollectionView into Icollectionview with filter?
– user6870932
Nov 21 '18 at 14:46
You can use ObservableCollection instead of List but as far as a QueryableCollectionView, this is something I've not heard of and looks from a quick Google to be a Telerik thing. Just give things a try and see what you come out with.
– Coops
Nov 21 '18 at 14:54
You can use ObservableCollection instead of List but as far as a QueryableCollectionView, this is something I've not heard of and looks from a quick Google to be a Telerik thing. Just give things a try and see what you come out with.
– Coops
Nov 21 '18 at 14:54
I've updated the code in the topic. Could you see what I'm doing wrong?
– user6870932
Nov 21 '18 at 15:30
I've updated the code in the topic. Could you see what I'm doing wrong?
– user6870932
Nov 21 '18 at 15:30
Use an ICollectionView instead of an ObservableCollection property, whatever you have in the View will bind to it.
– Coops
Nov 21 '18 at 15:32
Use an ICollectionView instead of an ObservableCollection property, whatever you have in the View will bind to it.
– Coops
Nov 21 '18 at 15:32
Let's say if I have a ICollectionView instead of that ObservableCollection, how would the code be? I guess I can just make do: private ICollectionView test = new ICollectionView(ObservableCollection)?
– user6870932
Nov 21 '18 at 16:06
Let's say if I have a ICollectionView instead of that ObservableCollection, how would the code be? I guess I can just make do: private ICollectionView test = new ICollectionView(ObservableCollection)?
– user6870932
Nov 21 '18 at 16:06
|
show 4 more comments
var test = CategoryCollection.GroupBy(Category => Category.Code).toList().Where(w => w.Count() > 1);
Can I use a observable collection?
– user6870932
Nov 20 '18 at 14:32
add a comment |
var test = CategoryCollection.GroupBy(Category => Category.Code).toList().Where(w => w.Count() > 1);
Can I use a observable collection?
– user6870932
Nov 20 '18 at 14:32
add a comment |
var test = CategoryCollection.GroupBy(Category => Category.Code).toList().Where(w => w.Count() > 1);
var test = CategoryCollection.GroupBy(Category => Category.Code).toList().Where(w => w.Count() > 1);
answered Nov 20 '18 at 14:17
Umar DrazUmar Draz
1
1
Can I use a observable collection?
– user6870932
Nov 20 '18 at 14:32
add a comment |
Can I use a observable collection?
– user6870932
Nov 20 '18 at 14:32
Can I use a observable collection?
– user6870932
Nov 20 '18 at 14:32
Can I use a observable collection?
– user6870932
Nov 20 '18 at 14:32
add a comment |
List<Category> listResult= yourObservableCollection.GroupBy(c => c.Code)
.Select(cl=>new Caegory
{
Code=cl.First().Code;
// other parameters of Category here
}).ToList().Where(w=>w.Count()>1);
ObservableCollection<Category> result=new ObservableCollection<Category>(listResult);
I don't know about QueryableCollectionView, but for ObservableCollection it works
add a comment |
List<Category> listResult= yourObservableCollection.GroupBy(c => c.Code)
.Select(cl=>new Caegory
{
Code=cl.First().Code;
// other parameters of Category here
}).ToList().Where(w=>w.Count()>1);
ObservableCollection<Category> result=new ObservableCollection<Category>(listResult);
I don't know about QueryableCollectionView, but for ObservableCollection it works
add a comment |
List<Category> listResult= yourObservableCollection.GroupBy(c => c.Code)
.Select(cl=>new Caegory
{
Code=cl.First().Code;
// other parameters of Category here
}).ToList().Where(w=>w.Count()>1);
ObservableCollection<Category> result=new ObservableCollection<Category>(listResult);
I don't know about QueryableCollectionView, but for ObservableCollection it works
List<Category> listResult= yourObservableCollection.GroupBy(c => c.Code)
.Select(cl=>new Caegory
{
Code=cl.First().Code;
// other parameters of Category here
}).ToList().Where(w=>w.Count()>1);
ObservableCollection<Category> result=new ObservableCollection<Category>(listResult);
I don't know about QueryableCollectionView, but for ObservableCollection it works
answered Nov 21 '18 at 6:31
Siegfried.VSiegfried.V
189114
189114
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53394545%2fwpf-c-sharp-how-can-i-filter-a-observablecollection-or-queryablecollectionview%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
You need an ICollectionView as shown here: wpftutorial.net/dataviews.html You can then get away with using a List instead of an ObservableCollection if you wish.
– Coops
Nov 20 '18 at 14:02
Does changes etc to the collection or the data also apply to this collection?
– user6870932
Nov 20 '18 at 14:04
If you were to use a List as the base property then I would say no, so in that case you can use an ObservableCollection as it would suit your needs. But whenever you change the filtering or something else you need to call .Refresh() on your ICollectionView
– Coops
Nov 20 '18 at 14:09
Hi, I'm not going to change the filter. I just want to list all the categories that is duplicated by checking if a code exist more than one time. I would like to use obseravblecollection for this, if it's possible to filter.
– user6870932
Nov 20 '18 at 14:13
It sounds very much like you're trying to do a couple of things with this collection. Are you trying to keep a collection with unique categories? If so then in your logic to add items you need to check for duplicates or even use a different type of collection, a dictionary for example. Also view which categories are duplicate, for what reason? If you can give a more complete explanation we can help more.
– Coops
Nov 20 '18 at 14:19