简体   繁体   中英

Using IEnumerable.Except

I got 3 listViews 2 textbox and 2 buttons in WinForm.

Program Description: The program adds numbers to the listview by typing in numbers in the textbox and clicking the add button

Goal: I want to be able to use the IEnumerable.Except method to output only the unique numbers in listView3 , for example in the picture below the unique numbers are 3 and 7 in listView1 and listView2 . ListViewItem lvi = new ListViewItem(textBox1.Text); listView1.Items.Add(lvi);

ListViewItem lv = new ListViewItem(textBox2.Text);
listView2.Items.Add(lv);

//im doing somthing wrong here...
var nonintersect = listView1.Except(listView2).Union(listView2.Except(listView1));

//populate listview3 with the unique numbers...
// foreach (item )
// {

// }

Error Message: System.Windows.Forms.ListView' does not contain a definition for 'Except' and no extension method 'Except' accepting a first argument of type 'System.Windows.Forms.ListView' could be found (are you missing a using directive or an assembly reference?)

在此输入图像描述

It's called Symmetric DIfference and it's simple as that.

var nonintersect = listView1.Except(listView2).Union(listView2.Except(listView1));

Source Origin

You can't do this with just Except , as it would only return { 3 } or just { 7 } in your example. However, if you take the set intersection between the two { 1, 2, 4 } and then use Except , you can get the de-intersection (which is basically what you are looking for):

IEnumerable<int> allObjects = list1.Concat(list2);
IEnumerable<int> intersection = list1.Intersect(list2);
IEnumerable<int> deIntersection = allObjects.Except(intersection);

You would need to do something like this:

IEnumerable<string> common =
        Enumerable
            .Intersect(
                listView1.Items.Cast<ListViewItem>().Select(x => x.Text),
                listView2.Items.Cast<ListViewItem>().Select(x => x.Text));

IEnumerable<string> all =
        Enumerable
            .Union(
                listView1.Items.Cast<ListViewItem>().Select(x => x.Text),
                listView2.Items.Cast<ListViewItem>().Select(x => x.Text));

IEnumerable<string> unique = all.Except(common);

Except is not defined for ListView . It's actually an extension method that is defined in System.Linq.Enumerable . You're probably confused because you can call Except from IList<T> (since IList<T> derives from IEnumerable<T> ), but what you're trying to do will never work because ListView doesn't inherit from IEnumerable<T> . The exception you're getting is the correct behavior.

To get the Except behavior for your controls, you'll need to manipulate the underlying collection and then bind the resulting collection object to the ListView control.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM