我有对象列表“orginalobject”如下图所示。这是从数据库
填充的 orginalobject.monitorName
orginalobject.ProcessGUID
orginalobject.Apikey
orginalobject.AIRSTATION
orginalobject.variableName
orginalobject.id
orginalobject.AIRSTATIONChannel
在附加图像中,您可以看到重复的某些列
monitorName
ProcessGUID
Apikey
AIRSTATION
不可重复的列是
variableName
id
AIRSTATIONChannel
所以我希望列表应该按这些重复列分组,其他列应该使用lamda或linq成为此对象的列表
object.monitorName
object.ProcessGUID
object.Apikey
object.AIRSTATION
Object.List<Subobjects> list
Subobjects类就像
ObjectSubobjects.variableName
ObjectSubobjects.id
ObjectSubobjects.AIRSTATIONChannel
答案 0 :(得分:0)
如果我理解你的问题是正确的,那么您只想按照用作非唯一monitorName
,ProcessGUID
,Apikey
和AIRSTATION
属性的对象列表进行分组键和每个组创建具有剩余唯一属性的子对象列表?
这可以通过以下简单的linq查询来完成。首先,它使用GroupBy
创建具有相同非唯一属性值的originalobjects
组。我使用ValueTuple
结构来表示非唯一属性的组合,作为用作分组键的单个对象。但是从提供的图像来看,似乎它可能是多余的,并且任何单独用作分组键的非唯一属性应该是足够的。查询的其余部分仅包含两个投影(Select
),可将值从originalobjects
复制到新创建的GroupObjects
和ObjectSubobjects
。
var groupedObjects = objects.GroupBy(o => (o.monitorName, o.ProcessGUID, o.Apikey, o.AIRSTATION))
.Select(g => new GroupObject()
{
monitorName = g.Key.monitorName,
ProcessGUID = g.Key.ProcessGUID,
Apikey = g.Key.Apikey,
AIRSTATION = g.Key.AIRSTATION,
list = g.Select(s => new ObjectSubobjects()
{
variableName = s.variableName,
id = s.id,
AIRSTATIONChannel = s.AIRSTATIONChannel
})
.ToList()
})
.ToList();
public class orginalobject
{
public string monitorName { get; set; }
public Guid ProcessGUID { get; set; }
public Guid Apikey { get; set; }
public string AIRSTATION { get; set; }
public string variableName { get; set; }
public Guid id { get; set; }
public int AIRSTATIONChannel { get; set; }
}
public class GroupObject
{
public string monitorName { get; set; }
public Guid ProcessGUID { get; set; }
public Guid Apikey { get; set; }
public string AIRSTATION { get; set; }
public List<ObjectSubobjects> list { get; set; }
}
public class ObjectSubobjects
{
public string variableName { get; set; }
public Guid id { get; set; }
public int AIRSTATIONChannel { get; set; }
}