Wednesday 27 December 2017

c# - group inside a list of objects and modify

itemprop="text">

I got a list from a class like this:




List
FinalValsLinks = new
List();


and
the class contains:



public class
clsLinkObject
{
public string clientCode { get; set; }

public string clienteName { get; set; }

public string units { get;
set; }


}


It is filled through
the program with FinalValsEnlaces.Add(myLinkObj);
So it ends up with a list of
objects whose clientCode can be repeated. I need to group up the repeated ones and add
its units:




  • select all the
    clientCode that are repeated.


  • Add all those
    units

  • Delete them and just add one with the total.



So, is there any easy
and straightforward way to do it, or just iterate through them and create a new
object?
In case the iteration way was the easier, would it be better to create
a new object or modify the one i
have?



foreach(var objadd in
FinalValsLinks)
{//count and add
string tmpclientN=
"";

tmpclientN = objadd.clientCode


...
}


thanks
in advance.


itemprop="text">
class="normal">Answer



You can
achieve it using Linq.




The below
linq statement, group based on the clientCode and return the
grouped (unique) records with sum of
units.



finalValsLinks =
finalValsLinks.GroupBy(f => f.clientCode).Select(g =>
{
var
first = g.First();
return new clsLinkObject() {clientCode = first.clientCode,
clienteName = first.clienteName, units = g.Sum(c => c.units)};

}).ToList();


I've
changed the definition of units to int. In case, you have
requirement to have units as string, then you can add the
int.Parse or double.Parse during the
Sum
operation.




See href="https://dotnetfiddle.net/RVvUUB" rel="nofollow noreferrer">this
dotnet fiddle created to demo the scenario.



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...