LINQ groupby with condition dependent on other sequence elements












0















LINQ. I have an IEnumerable of type Transaction:



private class Transaction{
public string Debitor { get; set; }
public double Debit { get; set; }
public string Creditor { get; set; } }


Sample IEnumerable<Transaction>:



[Debitor] | [Spend] | [Creditor]
luca 10 alessio
giulia 12 alessio
alessio 7 luca
alessio 6 giulia
marco 5 giulia
alessio 3 marco
luca 1 alessio


I would like to group the Transactions where Debitor == Creditor; else in a separate group. For the previous example, I should get:



  Group 1:
luca 10 alessio
alessio 7 luca
luca 1 alessio
Group 2:
giulia 12 alessio
alessio 6 giulia
Group 3:
marco 5 giulia
Group 4:
alessio 3 marco


I have solved it using 2 for loops (one nested) over the same IEnumerable, performing the check and using separate lists for the output, but I wonder if there is a less clunky way of doing this using LINQ.



A similar question might be: LINQ Conditional Group, however in this case the grouping condition is variable dependent on the other elements of the IEnumerable.










share|improve this question

























  • Hmm I think you should add more about your assumptions with groups here. Are you going to have groups with always two entries? Will there be leftover entries? Is there a possibility of duplicates and what should happen in these cases? What happens in case of a three-way group? Etc.

    – Jack
    Nov 26 '18 at 0:16











  • @Jack - see updated question. Thanks for spotting that.

    – alexlomba87
    Nov 26 '18 at 9:16
















0















LINQ. I have an IEnumerable of type Transaction:



private class Transaction{
public string Debitor { get; set; }
public double Debit { get; set; }
public string Creditor { get; set; } }


Sample IEnumerable<Transaction>:



[Debitor] | [Spend] | [Creditor]
luca 10 alessio
giulia 12 alessio
alessio 7 luca
alessio 6 giulia
marco 5 giulia
alessio 3 marco
luca 1 alessio


I would like to group the Transactions where Debitor == Creditor; else in a separate group. For the previous example, I should get:



  Group 1:
luca 10 alessio
alessio 7 luca
luca 1 alessio
Group 2:
giulia 12 alessio
alessio 6 giulia
Group 3:
marco 5 giulia
Group 4:
alessio 3 marco


I have solved it using 2 for loops (one nested) over the same IEnumerable, performing the check and using separate lists for the output, but I wonder if there is a less clunky way of doing this using LINQ.



A similar question might be: LINQ Conditional Group, however in this case the grouping condition is variable dependent on the other elements of the IEnumerable.










share|improve this question

























  • Hmm I think you should add more about your assumptions with groups here. Are you going to have groups with always two entries? Will there be leftover entries? Is there a possibility of duplicates and what should happen in these cases? What happens in case of a three-way group? Etc.

    – Jack
    Nov 26 '18 at 0:16











  • @Jack - see updated question. Thanks for spotting that.

    – alexlomba87
    Nov 26 '18 at 9:16














0












0








0


1






LINQ. I have an IEnumerable of type Transaction:



private class Transaction{
public string Debitor { get; set; }
public double Debit { get; set; }
public string Creditor { get; set; } }


Sample IEnumerable<Transaction>:



[Debitor] | [Spend] | [Creditor]
luca 10 alessio
giulia 12 alessio
alessio 7 luca
alessio 6 giulia
marco 5 giulia
alessio 3 marco
luca 1 alessio


I would like to group the Transactions where Debitor == Creditor; else in a separate group. For the previous example, I should get:



  Group 1:
luca 10 alessio
alessio 7 luca
luca 1 alessio
Group 2:
giulia 12 alessio
alessio 6 giulia
Group 3:
marco 5 giulia
Group 4:
alessio 3 marco


I have solved it using 2 for loops (one nested) over the same IEnumerable, performing the check and using separate lists for the output, but I wonder if there is a less clunky way of doing this using LINQ.



A similar question might be: LINQ Conditional Group, however in this case the grouping condition is variable dependent on the other elements of the IEnumerable.










share|improve this question
















LINQ. I have an IEnumerable of type Transaction:



private class Transaction{
public string Debitor { get; set; }
public double Debit { get; set; }
public string Creditor { get; set; } }


Sample IEnumerable<Transaction>:



[Debitor] | [Spend] | [Creditor]
luca 10 alessio
giulia 12 alessio
alessio 7 luca
alessio 6 giulia
marco 5 giulia
alessio 3 marco
luca 1 alessio


I would like to group the Transactions where Debitor == Creditor; else in a separate group. For the previous example, I should get:



  Group 1:
luca 10 alessio
alessio 7 luca
luca 1 alessio
Group 2:
giulia 12 alessio
alessio 6 giulia
Group 3:
marco 5 giulia
Group 4:
alessio 3 marco


I have solved it using 2 for loops (one nested) over the same IEnumerable, performing the check and using separate lists for the output, but I wonder if there is a less clunky way of doing this using LINQ.



A similar question might be: LINQ Conditional Group, however in this case the grouping condition is variable dependent on the other elements of the IEnumerable.







linq grouping aggregate






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 26 '18 at 9:15







alexlomba87

















asked Nov 25 '18 at 23:27









alexlomba87alexlomba87

170313




170313













  • Hmm I think you should add more about your assumptions with groups here. Are you going to have groups with always two entries? Will there be leftover entries? Is there a possibility of duplicates and what should happen in these cases? What happens in case of a three-way group? Etc.

    – Jack
    Nov 26 '18 at 0:16











  • @Jack - see updated question. Thanks for spotting that.

    – alexlomba87
    Nov 26 '18 at 9:16



















  • Hmm I think you should add more about your assumptions with groups here. Are you going to have groups with always two entries? Will there be leftover entries? Is there a possibility of duplicates and what should happen in these cases? What happens in case of a three-way group? Etc.

    – Jack
    Nov 26 '18 at 0:16











  • @Jack - see updated question. Thanks for spotting that.

    – alexlomba87
    Nov 26 '18 at 9:16

















Hmm I think you should add more about your assumptions with groups here. Are you going to have groups with always two entries? Will there be leftover entries? Is there a possibility of duplicates and what should happen in these cases? What happens in case of a three-way group? Etc.

– Jack
Nov 26 '18 at 0:16





Hmm I think you should add more about your assumptions with groups here. Are you going to have groups with always two entries? Will there be leftover entries? Is there a possibility of duplicates and what should happen in these cases? What happens in case of a three-way group? Etc.

– Jack
Nov 26 '18 at 0:16













@Jack - see updated question. Thanks for spotting that.

– alexlomba87
Nov 26 '18 at 9:16





@Jack - see updated question. Thanks for spotting that.

– alexlomba87
Nov 26 '18 at 9:16












2 Answers
2






active

oldest

votes


















1














The simplest way would indeed be to create a combined key, such as in Anu's answer.
Another way to do that (not necessarily better, but avoids sub collections and string joining), is:



var groups = transactions.GroupBy(t=> t.Debitor.CompareTo(t.Creditor) > 0 ? (t.Debitor,t.Creditor) : (t.Creditor,t.Debitor));


NB The above assumes you can use implicit Tuple creation. If you have a lower C# version and/or don't have the ValueTuple NuGet package installed, you can use: var groups = transactions.GroupBy(t=> t.Debitor.CompareTo(t.Creditor) > 0 ? Tuple.Create(t.Debitor,t.Creditor) : Tuple.Create(t.Creditor,t.Debitor));





Purely for the sake of mentioning it, another way, is to use a custom equality comparer for the group by. This might be overkill depending on your needs, collection size, need for reusabillity, etc, but to show the possibility all the same: first create a class (or implement it in Transaction directly)



class TransactionDebCredComparer : EqualityComparer<Transaction>
{
public override bool Equals(Transaction t1, Transaction t2) => (t1.Debitor == t2.Creditor && t2.Debitor == t1.Creditor) || (t1.Debitor == t2.Debitor && t2.Creditor == t1.Creditor);
public override int GetHashCode(Transaction t) => t.Debitor.GetHashCode() ^ t.Creditor.GetHashCode();
}


Then you can group your enumerable by using



var groups = transactions.GroupBy(t=>t, new TransactionDebCredComparer() );





share|improve this answer































    1














    For a simple solution, you could group using a key created with Creditor and Debitor. For example.



    string CreateKey(params string names)=>string.Join(",",names.OrderBy(x => x));
    var result = transactionCollection.GroupBy(x=> CreateKey(x.Debitor,x.Creditor));


    Please note I have used a collection in CreateKey, in case you have more similar grouping factors, but you can write a simpler version for CreateKey if the condition is always involving Creditor and Debitor alone.






    share|improve this answer


























    • Thanks, as pointed out by @Jack however I missed to clarify what should happen when there are "leftover" entries.

      – alexlomba87
      Nov 26 '18 at 10:32











    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53473038%2flinq-groupby-with-condition-dependent-on-other-sequence-elements%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    The simplest way would indeed be to create a combined key, such as in Anu's answer.
    Another way to do that (not necessarily better, but avoids sub collections and string joining), is:



    var groups = transactions.GroupBy(t=> t.Debitor.CompareTo(t.Creditor) > 0 ? (t.Debitor,t.Creditor) : (t.Creditor,t.Debitor));


    NB The above assumes you can use implicit Tuple creation. If you have a lower C# version and/or don't have the ValueTuple NuGet package installed, you can use: var groups = transactions.GroupBy(t=> t.Debitor.CompareTo(t.Creditor) > 0 ? Tuple.Create(t.Debitor,t.Creditor) : Tuple.Create(t.Creditor,t.Debitor));





    Purely for the sake of mentioning it, another way, is to use a custom equality comparer for the group by. This might be overkill depending on your needs, collection size, need for reusabillity, etc, but to show the possibility all the same: first create a class (or implement it in Transaction directly)



    class TransactionDebCredComparer : EqualityComparer<Transaction>
    {
    public override bool Equals(Transaction t1, Transaction t2) => (t1.Debitor == t2.Creditor && t2.Debitor == t1.Creditor) || (t1.Debitor == t2.Debitor && t2.Creditor == t1.Creditor);
    public override int GetHashCode(Transaction t) => t.Debitor.GetHashCode() ^ t.Creditor.GetHashCode();
    }


    Then you can group your enumerable by using



    var groups = transactions.GroupBy(t=>t, new TransactionDebCredComparer() );





    share|improve this answer




























      1














      The simplest way would indeed be to create a combined key, such as in Anu's answer.
      Another way to do that (not necessarily better, but avoids sub collections and string joining), is:



      var groups = transactions.GroupBy(t=> t.Debitor.CompareTo(t.Creditor) > 0 ? (t.Debitor,t.Creditor) : (t.Creditor,t.Debitor));


      NB The above assumes you can use implicit Tuple creation. If you have a lower C# version and/or don't have the ValueTuple NuGet package installed, you can use: var groups = transactions.GroupBy(t=> t.Debitor.CompareTo(t.Creditor) > 0 ? Tuple.Create(t.Debitor,t.Creditor) : Tuple.Create(t.Creditor,t.Debitor));





      Purely for the sake of mentioning it, another way, is to use a custom equality comparer for the group by. This might be overkill depending on your needs, collection size, need for reusabillity, etc, but to show the possibility all the same: first create a class (or implement it in Transaction directly)



      class TransactionDebCredComparer : EqualityComparer<Transaction>
      {
      public override bool Equals(Transaction t1, Transaction t2) => (t1.Debitor == t2.Creditor && t2.Debitor == t1.Creditor) || (t1.Debitor == t2.Debitor && t2.Creditor == t1.Creditor);
      public override int GetHashCode(Transaction t) => t.Debitor.GetHashCode() ^ t.Creditor.GetHashCode();
      }


      Then you can group your enumerable by using



      var groups = transactions.GroupBy(t=>t, new TransactionDebCredComparer() );





      share|improve this answer


























        1












        1








        1







        The simplest way would indeed be to create a combined key, such as in Anu's answer.
        Another way to do that (not necessarily better, but avoids sub collections and string joining), is:



        var groups = transactions.GroupBy(t=> t.Debitor.CompareTo(t.Creditor) > 0 ? (t.Debitor,t.Creditor) : (t.Creditor,t.Debitor));


        NB The above assumes you can use implicit Tuple creation. If you have a lower C# version and/or don't have the ValueTuple NuGet package installed, you can use: var groups = transactions.GroupBy(t=> t.Debitor.CompareTo(t.Creditor) > 0 ? Tuple.Create(t.Debitor,t.Creditor) : Tuple.Create(t.Creditor,t.Debitor));





        Purely for the sake of mentioning it, another way, is to use a custom equality comparer for the group by. This might be overkill depending on your needs, collection size, need for reusabillity, etc, but to show the possibility all the same: first create a class (or implement it in Transaction directly)



        class TransactionDebCredComparer : EqualityComparer<Transaction>
        {
        public override bool Equals(Transaction t1, Transaction t2) => (t1.Debitor == t2.Creditor && t2.Debitor == t1.Creditor) || (t1.Debitor == t2.Debitor && t2.Creditor == t1.Creditor);
        public override int GetHashCode(Transaction t) => t.Debitor.GetHashCode() ^ t.Creditor.GetHashCode();
        }


        Then you can group your enumerable by using



        var groups = transactions.GroupBy(t=>t, new TransactionDebCredComparer() );





        share|improve this answer













        The simplest way would indeed be to create a combined key, such as in Anu's answer.
        Another way to do that (not necessarily better, but avoids sub collections and string joining), is:



        var groups = transactions.GroupBy(t=> t.Debitor.CompareTo(t.Creditor) > 0 ? (t.Debitor,t.Creditor) : (t.Creditor,t.Debitor));


        NB The above assumes you can use implicit Tuple creation. If you have a lower C# version and/or don't have the ValueTuple NuGet package installed, you can use: var groups = transactions.GroupBy(t=> t.Debitor.CompareTo(t.Creditor) > 0 ? Tuple.Create(t.Debitor,t.Creditor) : Tuple.Create(t.Creditor,t.Debitor));





        Purely for the sake of mentioning it, another way, is to use a custom equality comparer for the group by. This might be overkill depending on your needs, collection size, need for reusabillity, etc, but to show the possibility all the same: first create a class (or implement it in Transaction directly)



        class TransactionDebCredComparer : EqualityComparer<Transaction>
        {
        public override bool Equals(Transaction t1, Transaction t2) => (t1.Debitor == t2.Creditor && t2.Debitor == t1.Creditor) || (t1.Debitor == t2.Debitor && t2.Creditor == t1.Creditor);
        public override int GetHashCode(Transaction t) => t.Debitor.GetHashCode() ^ t.Creditor.GetHashCode();
        }


        Then you can group your enumerable by using



        var groups = transactions.GroupBy(t=>t, new TransactionDebCredComparer() );






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 26 '18 at 11:22









        Me.NameMe.Name

        10.1k22039




        10.1k22039

























            1














            For a simple solution, you could group using a key created with Creditor and Debitor. For example.



            string CreateKey(params string names)=>string.Join(",",names.OrderBy(x => x));
            var result = transactionCollection.GroupBy(x=> CreateKey(x.Debitor,x.Creditor));


            Please note I have used a collection in CreateKey, in case you have more similar grouping factors, but you can write a simpler version for CreateKey if the condition is always involving Creditor and Debitor alone.






            share|improve this answer


























            • Thanks, as pointed out by @Jack however I missed to clarify what should happen when there are "leftover" entries.

              – alexlomba87
              Nov 26 '18 at 10:32
















            1














            For a simple solution, you could group using a key created with Creditor and Debitor. For example.



            string CreateKey(params string names)=>string.Join(",",names.OrderBy(x => x));
            var result = transactionCollection.GroupBy(x=> CreateKey(x.Debitor,x.Creditor));


            Please note I have used a collection in CreateKey, in case you have more similar grouping factors, but you can write a simpler version for CreateKey if the condition is always involving Creditor and Debitor alone.






            share|improve this answer


























            • Thanks, as pointed out by @Jack however I missed to clarify what should happen when there are "leftover" entries.

              – alexlomba87
              Nov 26 '18 at 10:32














            1












            1








            1







            For a simple solution, you could group using a key created with Creditor and Debitor. For example.



            string CreateKey(params string names)=>string.Join(",",names.OrderBy(x => x));
            var result = transactionCollection.GroupBy(x=> CreateKey(x.Debitor,x.Creditor));


            Please note I have used a collection in CreateKey, in case you have more similar grouping factors, but you can write a simpler version for CreateKey if the condition is always involving Creditor and Debitor alone.






            share|improve this answer















            For a simple solution, you could group using a key created with Creditor and Debitor. For example.



            string CreateKey(params string names)=>string.Join(",",names.OrderBy(x => x));
            var result = transactionCollection.GroupBy(x=> CreateKey(x.Debitor,x.Creditor));


            Please note I have used a collection in CreateKey, in case you have more similar grouping factors, but you can write a simpler version for CreateKey if the condition is always involving Creditor and Debitor alone.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 26 '18 at 3:14

























            answered Nov 26 '18 at 2:34









            Anu ViswanAnu Viswan

            4,8702524




            4,8702524













            • Thanks, as pointed out by @Jack however I missed to clarify what should happen when there are "leftover" entries.

              – alexlomba87
              Nov 26 '18 at 10:32



















            • Thanks, as pointed out by @Jack however I missed to clarify what should happen when there are "leftover" entries.

              – alexlomba87
              Nov 26 '18 at 10:32

















            Thanks, as pointed out by @Jack however I missed to clarify what should happen when there are "leftover" entries.

            – alexlomba87
            Nov 26 '18 at 10:32





            Thanks, as pointed out by @Jack however I missed to clarify what should happen when there are "leftover" entries.

            – alexlomba87
            Nov 26 '18 at 10:32


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53473038%2flinq-groupby-with-condition-dependent-on-other-sequence-elements%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Contact image not getting when fetch all contact list from iPhone by CNContact

            count number of partitions of a set with n elements into k subsets

            A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks