简体   繁体   中英

Create collection from another collection

I have a collection of objects with 3 properties

public class Match
{
    public string ReleaseNumber { get; set; }
    public string UnitNumber { get; set; }
    public float ConfidenceProbability { get; set; }
}

public class MatchReply
{
    public IEnumerable<Match> Matches { get; set; }
}

and I would like to create a new collection where the object is similar to the original in that it has the same properties minus one, ie

public class Release
{
    public string ReleaseNumber { get; set; }
    public float ConfidenceProbability { get; set; }
}

public class EventMessage
{
    public IEnumerable<Release> Releases { get; set; }
}

I thought of copying the collection, iterating through it and removing a property from each object - but this is more what I would do in Python. I also thought that I could create an extension of Match that I could call eg Match.ToRelease() but I can't figure out exactly how to apply it to the original collection.

What is the C# way of doing this?

You can also use LINQ for this.

private static IEnumerable<Match> getMatchList()
{
    List<Match> matchList = new List<Match>();

    matchList.Add(new Match {
        ConfidenceProbability = 1.0f,
        ReleaseNumber = "RELEASE#1",
        UnitNumber = "UNIT1"
    });

    matchList.Add(new Match
    {
        ConfidenceProbability = 2.0f,
        ReleaseNumber = "RELEASE#2",
        UnitNumber = "UNIT2"
    });

    return matchList;
}
var matchList = getMatchList();

var releaseList = matchList.Select(r => new Release {
    ConfidenceProbability = r.ConfidenceProbability,
    ReleaseNumber = r.ReleaseNumber
}).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM