2

I have the following ListView:

alt text

and I'm creating a List<string> of the items I want a list of rows to remove from that ListView:

List<String> lst =new List<String>{"A1","A2"};

I know that I can delete the rows using iterating through the index and deleting the item using RemoveAt() function, but is there any way to do this using LINQ?

2 Answers 2

1

As far as A1/A2 are the keys, no LINQ is required:

foeach(var a in new[] { "A1", "A2" })
    lw.Items.RemoveByKey(a);

Why not?


But if you want to use LINQ at any cost, write you own extension method:

public static void ForEach<T>(this IEnumerable<T> collection, Action<T> action)
{
    foreach (var item in collection)
        action(item);
}

and use it this way:

new[] { "A1", "A2" }.ForEach(a => lw.RemoveByKey(a));

However keep in mind that this is a well-known but disputable approach.

btw, List<T> already has such extension method, but my works for any IEnumerable<T>:

new List<string> { "A1", "A2" }.ForEach(); // evokes List<T>.ForEach
new[] { "A1", "A2" }.ForEach(); // evokes my
new List<string> { "A1", "A2" }.AsEnumerable().ForEach(); // evokes my, I guess
Sign up to request clarification or add additional context in comments.

3 Comments

If the List<String> contains more than two we can not do this right? But Iterating through the List we can do this. But i just need a LINQ approch( this is just for learning purpose only )
If you have a list like that you can iterate through the list and use the above mentioned solution. You should also be able to use lw.Items.RemoveByKey( string key).
The extension approach looks cool and "LINQ"y but seems to be overly complicated. I understand that this is just a learning example but the ListViewItemCollection is not really good for these things as it needs to be extended for the LINQ-things to work. There will be iteration somewhere, either tucked away in the extension method or more straight forward as in the former solution by abatishchev.
0

To do this, you can make a list of excluded items (and populate them however you want, but in this case I'm choosing a compile time list. Then you simply select all items in the first list and use the Except method to exclude items from the other list.

List<string> lst = new List<string>{"A1", "A2", "A3" };
List<string> excludedList = new List<string>{ "A1", "A2" };

var list = lst.Select(e => e)
              .Except(excludedList);

foreach (var a in list)
{
    Console.WriteLine(a + "\n"); //Displays A3
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.