Home > Net >  C# Linq - Return different Objects depending on Queryresult (if/else)
C# Linq - Return different Objects depending on Queryresult (if/else)

Time:10-14

I have a List which I query for some data under certain conditions it returns OKObject and under other conditions NotSoGoodObject. I would like to know how it´s possible to do this with Linq.

Basically:

var myList = context.Orders......ToList();
object obj=null;

if(myList.All(x=>x.myenum==1)){
  obj=OKObject {....};
 }
else if(myList.Any(x=>x.myenum==-1)){
 obj=NotSoGoodObject{....} ;
  }
}else{
 //No idea yet
}

I would have to do this for ~10 more enums.

Is there an way to do the above with one single Linq Query?

CodePudding user response:

I would try something along the lines of:

public List<object> GetDataObject(int enumInt) {
    var myList = context.Orders......ToList();
    return myList.Where(x => x.myenum == enumInt).ToList();
}

Although, I don't recommend using object.

CodePudding user response:

The only way that seems possible, is if you had a Class, for example NumbersGoodEnough, and one of it's properties was set with a linq query

But that only makes your code look cleaner here

Or simply try using a method to put all of the code in, that would be my first choice

  • Related