开发者

LINQ request [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.

Want to improve this question? Add details and clarify the problem by editing this post.

Closed 3 years ago.

开发者_StackOverflow Improve this question

How to do this?

int[] mas={1,2,3,4,...,n}

public var method1(mas)
{
var d = from i in Object where i.number==mas[0] || i.number==mas[1] || i.number==mas[2]|| ... || i.number==mas[n] select i;
return d;
}


You will want to do something like this

var d = From i in Object
        From n in mas
        Where n == i.Number
        Select i;
return d;

Actually now that I think about that, that is going to return to you a list of i for every match.

You probably were looking for something more like

   //create a list for the items that match the criteria
    List<ObjectToGet> d = new List<ObjectToGet>;

    //Loop over each item in your Object
    foreach(ObjectToGet objectItem in Object){
        //If the item contains any match add it to the list
        if((From n in mas Where n == d.Number Select n).Any){
            d.Add(objectItem);
        }
    }

    return d;

There's probably a way to write this in pure LINQ but this is conceptually what you are trying to do


Wrap your mas into HashSet by using constructor and use Contains

Check this article as inroduction: Introducing HashSet (Kim Hamilton)

So you'll end with something like that:

 int[] mas={1,2,3,4,...,n};
 var set = new HashSet<int>(mas); // or you can init set with proper value without array

 public var method1(mas)
 {
    var d = from i in Object where set.Contains(i.number) select i;
    return d;
 }

Pure LINQ solution is good too (@msarchet) when you have small enough source array.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜