如何使用LINQ选择到对象? [英] How to use LINQ to select into an object?

查看:100
本文介绍了如何使用LINQ选择到对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的数据:

 用户ID | SongId
--------
1 1
1 4
1月12日
2 95
 

我也有下面的类:

 类SongsForUser
{
    公众诠释用户;
    公开名单< INT>歌曲;
}
 

我希望做的是使用LINQ从我的数据来选择要创建SongsForUser对象的集合。下面是我想出迄今:

  VAR userCombos = songs.UserSongs.Select(X =>新建SongsForUser(){USER = x.UserId,
                                                                  歌曲= / *善有善报在这里* /})?;
 

我怎么会去填充我的歌曲列表?

因此​​,结果应该是两个SongsForUser对象。对于用户 1 ,将有3个项目在歌曲列表。对于用户 2 它会在歌曲项列表。

解决方案

  songs.UserSongs.GroupBy(X => x.User)。选择(G =>新建SongsForUser( )
{
    用户= g.Key,
    歌曲= g.Select(S => s.SongId).ToList()
});
 

I have data that looks like so:

UserId   |  SongId
--------   --------
1          1
1          4
1          12
2          95

I also have the following class:

class SongsForUser
{
    public int User;
    public List<int> Songs;
}

What I would like to do is use LINQ to select from my data to create a collection of SongsForUser objects. Below is what I have come up with so far:

var userCombos = songs.UserSongs.Select(x => new SongsForUser() { User = x.UserId, 
                                                                  Songs = /*What goes here?*/ });

How would I go about populating my Songs List?

So the result should be two SongsForUser objects. For user 1 it would have 3 items in the Songs list. For user 2 it would have 1 item in the Songs list.

解决方案

songs.UserSongs.GroupBy(x => x.User).Select(g => new SongsForUser() 
{ 
    User = g.Key,
    Songs = g.Select(s => s.SongId).ToList()
});

这篇关于如何使用LINQ选择到对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆