Hello!
Please tell me how to rewrite the function GetValues() using LINQ.
And if you give a sensible link to learning LINQ (except for MSDN), I will be grateful.

Here is the code:

 enum MyEnum { FIRST, SECOND }; class MyClass { List<MyObject> MyList = new List<MyObject>(); //constructor internal MyClass() { MyList.Add(new MyObject(MyEnum.FIRST, 1)); MyList.Add(new MyObject(MyEnum.FIRST, 2)); MyList.Add(new MyObject(MyEnum.FIRST, 3)); MyList.Add(new MyObject(MyEnum.SECOND, 1)); List<int> collectedValues = GetValues(MyList, MyEnum.SECOND); } List<int> GetValues(List<MyObject> MyList, MyEnum ExceptionEnum) { List<int> returnList = new List<int>(); for(int i = 0; i < MyList.Count; i++) { if(MyList[i].MyName == ExceptionEnum) continue; returnList.Add(MyList[i].Value); } return returnList; } } class MyObject { internal MyEnum MyName; internal int Value; public MyObject(MyEnum MyName, int Value) { this.MyName = MyName; this.Value = Value; } } 
  • There is hardly anything better than MSDN - Grundy
  • C # literature . - Alexander Petrov

1 answer 1

Sort of:

 List<int> GetValues(List<MyObject> MyList, MyEnum ExceptionEnum) { return MyList.Where(i => i.MyName != ExceptionEnum).Select(i => i.Value).ToList(); } 

Your code:

 if(MyList[i].MyName == ExceptionEnum) continue; returnList.Add(MyList[i].Value); 

It will be equal to:

 if(MyList[i].MyName != ExceptionEnum) returnList.Add(MyList[i].Value); 

And it follows from this that we need to take all the elements from MyList , where MyListItem.MyName != ExceptionEnum . Here we are come to the aid of Where-clause . Next, we pass and pull the Value out of each element using Select-clause . And at the end we simply convert IEnumerable to List using ToList() .

As for the study of LINQ, I will advise the site of Comrade Metanite .

  • Where in this case is not enough. Look at what values ​​it adds to the list that returns - Grundy
  • @Grundy inattention is my misfortune. Thank you, corrected - MihailPw
  • Thanks for your reply - K.Oleg