1

New to LINQ and trying to figure out how to exclude an item from a list. I have a list of names and their position level. Which looks like

Name    ID    Level
aaa     123   0
bbb     122   1
ccc     222   2
ddd     223   3

What I'm trying to do is figure out a way to exclude the record with the highest level. I'm refactoring some code that was using a for loop to check for this and I'm having a hard time figuring out how to mirror that.

1
  • 2
    Are all Level values different and unique? Commented Mar 27, 2018 at 15:21

4 Answers 4

1

Exact structure of your types is not clear, but something like this:

list.OrderBy(x=>x.Level).Take(list.Count-1) //where x is an Item (Raw) from he list

should work foryou.

if you might have multiple MAX values just use Distinct (see examples in documentation how to use it)

if you might have multiple repetitive values in collection (including non MAX values), you might do

list.OrderByDescending(x => x.Level);
var max = list.First();
var result = list.SkipWhile(x=>x == max);
Sign up to request clarification or add additional context in comments.

2 Comments

Did you originally post: list.OrderBy(x => x.Level).Take(list.Count - 1).ToList(); because that worked perfectly. Thank you!
@TrevorGoodchild: you on't need ToList()if you intend to siply iterate over result.
1

The simplest way is:

var max = list
    .Max(l => l.Level);

var listWithoutMax = list
    .Where(l => l.Level != max);

Comments

1

This small code snippet should work fine:

Int32 max = list.Max(x => x.Level);
List<MyObject> newList = list.Where(x => x.Level != max).ToList();

and, if your list contains more than one element with the maximum level value, will ensure that all of them will be removed from it.

Comments

0

You can use RemoveAll():

var result = list.RemoveAll(x => x.Level == list.Max(s => s.Level));

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.