4

I have a List such as below.

List<int> temp = new List<int> { 3, 5, 6, 8, 2, 1, 6};

I'm going to use a LINQ to remove Min and Max value in Above List.

For example, below snippet code is just example, not working.

var newValue = from pair in temp
               select pair < temp.Max() && pair > temp.Min()

Hopefully, I expect the result like below ;

newValue = {3, 5, 6, 2, 6 }

I've tried Googling, but couldn't find proper example yet.

Is it workigng when I use a LINQ ? Thanks for your time.

2
  • What happens when you run the code? Commented Oct 30, 2014 at 4:32
  • Doesn't work. just null. Commented Oct 30, 2014 at 4:40

4 Answers 4

5

You should be using where.

from pair in temp
where pair < temp.Max() && pair > temp.Min()
select pair

Your current approach will select whether the values are in range, not filter them. That's what the where clause is for.

Sign up to request clarification or add additional context in comments.

Comments

5

Try this:-

var query = temp.Where(x => x != temp.Min() && x != temp.Max()).ToList();

Working Fiddle.

1 Comment

Nice! Note that it will remove all the min and max values if there are any duplicates.
0

if you just need to remove the min and max values you why not just use remove()? what's the need for the pair?

    List<int> temp =new List<int>() { 3, 5, 6, 8, 2, 1, 6 };
    temp.Remove(temp.Max());
    temp.Remove(temp.Min());

or something like this if you need to maintain temp and would rather work on a copy

temp.Sort();
temp.Skip(1).Take(temp.Count - 2).ToList();

Comments

0

How could you be able to add an array in Generic Collection. Also you have to convert your query result into list. Use the where clause as suggested by @Matthew Haugen.

List<int> temp = new List<int>();// {3, 5, 6, 8, 2, 1, 6}

temp.Add(3);
temp.Add(5);
temp.Add(6);
temp.Add(8);
temp.Add(2);
temp.Add(1);
temp.Add(6);

List<int> newValue = (from n in temp 
                      where n > temp.Min() & n < temp.Max() 
                      Select n).ToList();

1 Comment

It depends on the use I think, you don't necessarily need to convert it to list. :)

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.