Check for Values in Linq Query

lesponce 176 Reputation points
2022-09-23T17:22:30.697+00:00

I got a query that is working fine checking for a value inside the query. However, now I need to check for multiple values coming from a string. The values in the string came from an array.

In this example: a.FieldName is equal to 'ABC'
For example in my linq query this wokrs fine: FieldName = a.FieldName = ?? "",

Now, I need to check for multiple values. If it would be an IF statement, I can use OR contidition.
The value that I need to handle is like this: p1.FieldName is 'ABC,XYZ,FYZ'.

How can I accomplish this? As it could have multiple values, it can have just one, or empty (no value).

The code goes like this:

var MyVariable = period1.Join(  
period2,  
p1 => p1.field1,  
p2 => p2.field1,  
(p1, p2) => new MyClass()  
{  
    FieldName = p1.FieldName ?? "",     // This works with one value. I need it to handle multi values.  
   AnotherField = p1.AnotherField ?? ""  
}  
).ToList();  
  
.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,264 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,098 questions
{count} votes

Accepted answer
  1. Jack J Jun 24,276 Reputation points Microsoft Vendor
    2022-09-26T07:47:37.37+00:00

    @lesponce , Welcome to Microsoft Q&A, I recommend that you used ternary conditional operator to check if the value is equal to the item from the array.

    Here is a code example you could refer to.

    code.txt

    Result:

    244713-image.png

    Hope this could help you.

    Best Regards,
    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful