开发者

linq query: list as input parameter

开发者 https://www.devze.com 2023-02-20 17:55 出处:网络
Let\'s say we have 2 object models: class MyModel1{ int ModelID {get;set;} string Var2 {get;set;} } class MyModel2{

Let's say we have 2 object models:

class MyModel1{
   int ModelID {get;set;}
   string Var2 {get;set;}
}

class MyModel2{
   int ModelID {get;set;}
   string Var2 {get;set;}
}

Let's say that we have a linq to sql query that returns a list of MyModel1 like this:

var OutputModel1 = from t in MyDataContext
            where...
            select new MyModel1
            {...}.ToList();

Return OutputModel1 as List<MyModel1>;

Now that I have this list, I'd like to pass this l开发者_C百科ist to another query that'll return a list of of MyModel2 where the ModelID is the same.

Let me know if you have some suggestions on how to do this.

Thanks.


If you simply want to make a MyModel2 copy of each MyModel1 some point afterwards, then it's simple:

var OutputModel2 = OutputModel1.Select(m =>
    new MyModel2 { 
        ModelId = m.ModelId,
        Var2 = m.Var2,
    }).ToList();

If you need to query the data context for those MyModel2 objects with the same ids as the MyModel1 objects (i.e., there is a relation), then it's different (but you should provide that information).

PS: There's no need to write as List<MyModel1> -- the return value of ToList is exactly a List<MyModel1>, no more, no less.


var OutputModel2 = (from m in MyDataContext.Model2Collection where MyDataContext.Model1Collection.Any(x => x.ModelID == m.ModelID && x.Var2 == 3/*PUT YOUR WHERE CLAUSE HERE*/)).ToList();


Assuming that you're looking for a subset of existing Model2's, you could use something like the following:

var OutputModel2 = from t2 in CollectionOfModel2s
                           join t1 in OutputModel1 on t2.ModelID equals t1.ModelID
                           select t2;

The "join" functions like an inner join in SQL, and won't return any t2's that don't have a match.

There's a fairly detailed description of joins and whatnot at: http://msdn.microsoft.com/en-us/library/bb397941.aspx#Y275

0

精彩评论

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