1
votes

I have a immutable List.

In the below g.Select(...) I do a .ToList() which is put into the MemberIdList. I do not want to create a new List with ToList() rather I want to add each r.Field string to the immutable List inside the unit object.

How can I do this?

var groupedCollection = table.AsEnumerable()
        .GroupBy(row => new
        {
            UType = row.Field<string>("UnitType"),
            UZoom = row.Field<string>("UnitZoom"),
            MZoom = row.Field<string>("MemberZoom"),
        });

    var unitCollection = groupedCollection
        .Select(g => new Unit
        {
            UnitType = g.Key.UType,
            UnitZoom = g.Key.UZoom,
            MemberZoom = g.Key.MZoom,
            MemberIdList = g.Select(r => r.Field<string>("TestId")).ToList(),
        });

    List<Unit> units = unitCollection.ToList();


public class Unit
{
    public Unit()
    {
        MemberIdList = new List<String>();
    }

    public String UnitType { get; set; }
    public String UnitZoom { get; set; }
    public String MemberZoom { get; set; }
    public int MemberOrder { get; set; }

    public List<String> MemberIdList { get; private set; }
}
1
In my context MemberIdList.AddRange(g.Select(r => r.Field<string>("TestId"))); does not work. Typing MemberIdList. there is no AddRange. - msfanboy
@msfanboy are you sure it is a List<T> then? As that definitely has AddRange. You will of course need to tell it the instance, I.e. Obj.MemberIdList.AddRange() - Marc Gravell
Btw ; List<T> is never immutable. A list-property without a setter is very different to an immutable list. - Marc Gravell
but I have a private setter?? - msfanboy
@msfanboy so? that just means you can't change it to a different list. I can still call yourList.Add(x) - the list is not internally immutable. - Marc Gravell

1 Answers

2
votes

Why not just create a constructor for Unit that takes the data for MemberIdList like:

public Unit(IEnumerable<string> memberIdList)
{
    MemberIdList = new List<string>(memberIdList);
}

and modify your select to:

.Select(g => new Unit(g.Select(r => r.Field<string>("TestId")))
{
    UnitType = g.Key.UType,
    UnitZoom = g.Key.UZoom,
    MemberZoom = g.Key.MZoom
});