LINQ groupby with condition dependent on other sequence elements
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 Transaction
s 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
add a comment |
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 Transaction
s 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
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
add a comment |
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 Transaction
s 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
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 Transaction
s 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
linq grouping aggregate
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
add a comment |
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
add a comment |
2 Answers
2
active
oldest
votes
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() );
add a comment |
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.
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
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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() );
add a comment |
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() );
add a comment |
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() );
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() );
answered Nov 26 '18 at 11:22
Me.NameMe.Name
10.1k22039
10.1k22039
add a comment |
add a comment |
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.
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
add a comment |
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.
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
add a comment |
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.
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.
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
add a comment |
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
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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