What is the simplest way to partition a list based on a criteria?
Let's say, we have an object definition like this,
class MyObject {
int id;
string name;
}
and we have a list of MyObjects.
List<MyObject> objectList
Now, I need to partition this objectList into 2 sub-lists based on which objects have a non-null name field.
So, after the operation, I need to have 2 lists, objectsWithName
where name field is non-null and objectsWithoutName
where name field is null (this is the immediate criteria, but I'm looking more towards partitioning into 2 groups using a predicate).
What is the simplest way to achieve this? Can I do this in a single operation? Using LINQ is permitted.
c# list linq ienumerable
add a comment |
Let's say, we have an object definition like this,
class MyObject {
int id;
string name;
}
and we have a list of MyObjects.
List<MyObject> objectList
Now, I need to partition this objectList into 2 sub-lists based on which objects have a non-null name field.
So, after the operation, I need to have 2 lists, objectsWithName
where name field is non-null and objectsWithoutName
where name field is null (this is the immediate criteria, but I'm looking more towards partitioning into 2 groups using a predicate).
What is the simplest way to achieve this? Can I do this in a single operation? Using LINQ is permitted.
c# list linq ienumerable
4
for loop with if statement would be simplest, LINQ is overhead here
– brykneval
Nov 21 '18 at 9:03
1
This would help you stackoverflow.com/questions/419019/…
– Hamza Haider
Nov 21 '18 at 9:10
@brykneval - what makes you think Linq is an overhead -- have you compared the IL generated by a foreach loop with that generated by Linq? I think you'll find they are not very different.
– Chris F Carroll
Nov 21 '18 at 9:17
add a comment |
Let's say, we have an object definition like this,
class MyObject {
int id;
string name;
}
and we have a list of MyObjects.
List<MyObject> objectList
Now, I need to partition this objectList into 2 sub-lists based on which objects have a non-null name field.
So, after the operation, I need to have 2 lists, objectsWithName
where name field is non-null and objectsWithoutName
where name field is null (this is the immediate criteria, but I'm looking more towards partitioning into 2 groups using a predicate).
What is the simplest way to achieve this? Can I do this in a single operation? Using LINQ is permitted.
c# list linq ienumerable
Let's say, we have an object definition like this,
class MyObject {
int id;
string name;
}
and we have a list of MyObjects.
List<MyObject> objectList
Now, I need to partition this objectList into 2 sub-lists based on which objects have a non-null name field.
So, after the operation, I need to have 2 lists, objectsWithName
where name field is non-null and objectsWithoutName
where name field is null (this is the immediate criteria, but I'm looking more towards partitioning into 2 groups using a predicate).
What is the simplest way to achieve this? Can I do this in a single operation? Using LINQ is permitted.
c# list linq ienumerable
c# list linq ienumerable
edited Nov 21 '18 at 9:21


Foo
1
1
asked Nov 21 '18 at 9:01


Sayan BoseSayan Bose
44429
44429
4
for loop with if statement would be simplest, LINQ is overhead here
– brykneval
Nov 21 '18 at 9:03
1
This would help you stackoverflow.com/questions/419019/…
– Hamza Haider
Nov 21 '18 at 9:10
@brykneval - what makes you think Linq is an overhead -- have you compared the IL generated by a foreach loop with that generated by Linq? I think you'll find they are not very different.
– Chris F Carroll
Nov 21 '18 at 9:17
add a comment |
4
for loop with if statement would be simplest, LINQ is overhead here
– brykneval
Nov 21 '18 at 9:03
1
This would help you stackoverflow.com/questions/419019/…
– Hamza Haider
Nov 21 '18 at 9:10
@brykneval - what makes you think Linq is an overhead -- have you compared the IL generated by a foreach loop with that generated by Linq? I think you'll find they are not very different.
– Chris F Carroll
Nov 21 '18 at 9:17
4
4
for loop with if statement would be simplest, LINQ is overhead here
– brykneval
Nov 21 '18 at 9:03
for loop with if statement would be simplest, LINQ is overhead here
– brykneval
Nov 21 '18 at 9:03
1
1
This would help you stackoverflow.com/questions/419019/…
– Hamza Haider
Nov 21 '18 at 9:10
This would help you stackoverflow.com/questions/419019/…
– Hamza Haider
Nov 21 '18 at 9:10
@brykneval - what makes you think Linq is an overhead -- have you compared the IL generated by a foreach loop with that generated by Linq? I think you'll find they are not very different.
– Chris F Carroll
Nov 21 '18 at 9:17
@brykneval - what makes you think Linq is an overhead -- have you compared the IL generated by a foreach loop with that generated by Linq? I think you'll find they are not very different.
– Chris F Carroll
Nov 21 '18 at 9:17
add a comment |
3 Answers
3
active
oldest
votes
Two LINQ statements would do:
var nameNotNull = objectList.Where(o => !string.IsNullOrEmpty(o.Name));
var nameNull = objectList.Where(o => string.IsNullOrEmpty(o.Name));
Of course, you could use GroupBy
, or a more efficient foreach
statement.
To show the foreach
option:
List<MyObject> nameNotNull = new List<MyObject>();
List<MyObject> nameNull = new List<MyObject>();
foreach (MyObject o in objectList)
{
if (!string.IsNullOrEmpty(o.Name))
{
nameNotNull.Add(o);
}
else
{
nameNull.Add(o);
}
}
I was looking to partition the list in a single iteration - so I would go with the foreach solution.
– Sayan Bose
Nov 21 '18 at 10:12
That is perfectly fine. @SayanBose
– Patrick Hofman
Nov 21 '18 at 10:30
add a comment |
public class MyObject
{
public int Id { get; set; }
public string Name { get; set; }
}
public class MyObjectLists
{
private readonly List<MyObject> _objects;
public List<MyObject> NullNameObjects
{
get
{
return _objects.Where(x => x.Name == null).ToList();
}
}
public List<MyObject> NonNullNameObjects
{
get
{
return _objects.Where(x => x.Name != null).ToList();
}
}
public MyObjectLists(List<MyObject> objects)
{
_objects = objects ?? throw new ArgumentNullException(nameof(objects));
}
}
Using the code:
var list = new List<MyObject>
{
new MyObject
{
Id = 1,
Name = "John"
},
new MyObject
{
Id = 2
},
new MyObject
{
Id = 3,
Name = "Mary"
},
new MyObject
{
Id = 4
}
};
var objects = new MyObjectLists(list);
foreach (MyObject myObject in objects.NonNullNameObjects)
{
Console.WriteLine($"Object with Id {myObject.Id} has a non-null name");
}
foreach (MyObject myObject in objects.NullNameObjects)
{
Console.WriteLine($"Object with Id {myObject.Id} has a null name");
}
add a comment |
I think you're looking for something like this example:
class MyObject
{
int id;
string name;
}
var objectList = new List<MyObject>();
objectList.Add(new MyObject { name = "item 1" });
objectList.Add(new MyObject { name = string.Empty });
objectList.Add(new MyObject { name = "item 3" });
var objectsWithName = objectList.Where(x => !string.IsNullOrEmpty(x.name));
var objectsWithoutName = objectList.Except(objectsWithName);
I've created 2 lists that the first list contains the MyObject
items with the name
property is NOT null, otherwise to the second's.
Except
is too expensive here.
– Patrick Hofman
Nov 21 '18 at 9:37
@PatrickHofman I'm sorry. Could you please explain why?
– Foo
Nov 21 '18 at 9:46
1
Because it will create a hashset to compare values, while there is absolutely no need for.
– Patrick Hofman
Nov 21 '18 at 9:50
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%2f53408452%2fwhat-is-the-simplest-way-to-partition-a-list-based-on-a-criteria%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
Two LINQ statements would do:
var nameNotNull = objectList.Where(o => !string.IsNullOrEmpty(o.Name));
var nameNull = objectList.Where(o => string.IsNullOrEmpty(o.Name));
Of course, you could use GroupBy
, or a more efficient foreach
statement.
To show the foreach
option:
List<MyObject> nameNotNull = new List<MyObject>();
List<MyObject> nameNull = new List<MyObject>();
foreach (MyObject o in objectList)
{
if (!string.IsNullOrEmpty(o.Name))
{
nameNotNull.Add(o);
}
else
{
nameNull.Add(o);
}
}
I was looking to partition the list in a single iteration - so I would go with the foreach solution.
– Sayan Bose
Nov 21 '18 at 10:12
That is perfectly fine. @SayanBose
– Patrick Hofman
Nov 21 '18 at 10:30
add a comment |
Two LINQ statements would do:
var nameNotNull = objectList.Where(o => !string.IsNullOrEmpty(o.Name));
var nameNull = objectList.Where(o => string.IsNullOrEmpty(o.Name));
Of course, you could use GroupBy
, or a more efficient foreach
statement.
To show the foreach
option:
List<MyObject> nameNotNull = new List<MyObject>();
List<MyObject> nameNull = new List<MyObject>();
foreach (MyObject o in objectList)
{
if (!string.IsNullOrEmpty(o.Name))
{
nameNotNull.Add(o);
}
else
{
nameNull.Add(o);
}
}
I was looking to partition the list in a single iteration - so I would go with the foreach solution.
– Sayan Bose
Nov 21 '18 at 10:12
That is perfectly fine. @SayanBose
– Patrick Hofman
Nov 21 '18 at 10:30
add a comment |
Two LINQ statements would do:
var nameNotNull = objectList.Where(o => !string.IsNullOrEmpty(o.Name));
var nameNull = objectList.Where(o => string.IsNullOrEmpty(o.Name));
Of course, you could use GroupBy
, or a more efficient foreach
statement.
To show the foreach
option:
List<MyObject> nameNotNull = new List<MyObject>();
List<MyObject> nameNull = new List<MyObject>();
foreach (MyObject o in objectList)
{
if (!string.IsNullOrEmpty(o.Name))
{
nameNotNull.Add(o);
}
else
{
nameNull.Add(o);
}
}
Two LINQ statements would do:
var nameNotNull = objectList.Where(o => !string.IsNullOrEmpty(o.Name));
var nameNull = objectList.Where(o => string.IsNullOrEmpty(o.Name));
Of course, you could use GroupBy
, or a more efficient foreach
statement.
To show the foreach
option:
List<MyObject> nameNotNull = new List<MyObject>();
List<MyObject> nameNull = new List<MyObject>();
foreach (MyObject o in objectList)
{
if (!string.IsNullOrEmpty(o.Name))
{
nameNotNull.Add(o);
}
else
{
nameNull.Add(o);
}
}
answered Nov 21 '18 at 9:06


Patrick HofmanPatrick Hofman
127k18171229
127k18171229
I was looking to partition the list in a single iteration - so I would go with the foreach solution.
– Sayan Bose
Nov 21 '18 at 10:12
That is perfectly fine. @SayanBose
– Patrick Hofman
Nov 21 '18 at 10:30
add a comment |
I was looking to partition the list in a single iteration - so I would go with the foreach solution.
– Sayan Bose
Nov 21 '18 at 10:12
That is perfectly fine. @SayanBose
– Patrick Hofman
Nov 21 '18 at 10:30
I was looking to partition the list in a single iteration - so I would go with the foreach solution.
– Sayan Bose
Nov 21 '18 at 10:12
I was looking to partition the list in a single iteration - so I would go with the foreach solution.
– Sayan Bose
Nov 21 '18 at 10:12
That is perfectly fine. @SayanBose
– Patrick Hofman
Nov 21 '18 at 10:30
That is perfectly fine. @SayanBose
– Patrick Hofman
Nov 21 '18 at 10:30
add a comment |
public class MyObject
{
public int Id { get; set; }
public string Name { get; set; }
}
public class MyObjectLists
{
private readonly List<MyObject> _objects;
public List<MyObject> NullNameObjects
{
get
{
return _objects.Where(x => x.Name == null).ToList();
}
}
public List<MyObject> NonNullNameObjects
{
get
{
return _objects.Where(x => x.Name != null).ToList();
}
}
public MyObjectLists(List<MyObject> objects)
{
_objects = objects ?? throw new ArgumentNullException(nameof(objects));
}
}
Using the code:
var list = new List<MyObject>
{
new MyObject
{
Id = 1,
Name = "John"
},
new MyObject
{
Id = 2
},
new MyObject
{
Id = 3,
Name = "Mary"
},
new MyObject
{
Id = 4
}
};
var objects = new MyObjectLists(list);
foreach (MyObject myObject in objects.NonNullNameObjects)
{
Console.WriteLine($"Object with Id {myObject.Id} has a non-null name");
}
foreach (MyObject myObject in objects.NullNameObjects)
{
Console.WriteLine($"Object with Id {myObject.Id} has a null name");
}
add a comment |
public class MyObject
{
public int Id { get; set; }
public string Name { get; set; }
}
public class MyObjectLists
{
private readonly List<MyObject> _objects;
public List<MyObject> NullNameObjects
{
get
{
return _objects.Where(x => x.Name == null).ToList();
}
}
public List<MyObject> NonNullNameObjects
{
get
{
return _objects.Where(x => x.Name != null).ToList();
}
}
public MyObjectLists(List<MyObject> objects)
{
_objects = objects ?? throw new ArgumentNullException(nameof(objects));
}
}
Using the code:
var list = new List<MyObject>
{
new MyObject
{
Id = 1,
Name = "John"
},
new MyObject
{
Id = 2
},
new MyObject
{
Id = 3,
Name = "Mary"
},
new MyObject
{
Id = 4
}
};
var objects = new MyObjectLists(list);
foreach (MyObject myObject in objects.NonNullNameObjects)
{
Console.WriteLine($"Object with Id {myObject.Id} has a non-null name");
}
foreach (MyObject myObject in objects.NullNameObjects)
{
Console.WriteLine($"Object with Id {myObject.Id} has a null name");
}
add a comment |
public class MyObject
{
public int Id { get; set; }
public string Name { get; set; }
}
public class MyObjectLists
{
private readonly List<MyObject> _objects;
public List<MyObject> NullNameObjects
{
get
{
return _objects.Where(x => x.Name == null).ToList();
}
}
public List<MyObject> NonNullNameObjects
{
get
{
return _objects.Where(x => x.Name != null).ToList();
}
}
public MyObjectLists(List<MyObject> objects)
{
_objects = objects ?? throw new ArgumentNullException(nameof(objects));
}
}
Using the code:
var list = new List<MyObject>
{
new MyObject
{
Id = 1,
Name = "John"
},
new MyObject
{
Id = 2
},
new MyObject
{
Id = 3,
Name = "Mary"
},
new MyObject
{
Id = 4
}
};
var objects = new MyObjectLists(list);
foreach (MyObject myObject in objects.NonNullNameObjects)
{
Console.WriteLine($"Object with Id {myObject.Id} has a non-null name");
}
foreach (MyObject myObject in objects.NullNameObjects)
{
Console.WriteLine($"Object with Id {myObject.Id} has a null name");
}
public class MyObject
{
public int Id { get; set; }
public string Name { get; set; }
}
public class MyObjectLists
{
private readonly List<MyObject> _objects;
public List<MyObject> NullNameObjects
{
get
{
return _objects.Where(x => x.Name == null).ToList();
}
}
public List<MyObject> NonNullNameObjects
{
get
{
return _objects.Where(x => x.Name != null).ToList();
}
}
public MyObjectLists(List<MyObject> objects)
{
_objects = objects ?? throw new ArgumentNullException(nameof(objects));
}
}
Using the code:
var list = new List<MyObject>
{
new MyObject
{
Id = 1,
Name = "John"
},
new MyObject
{
Id = 2
},
new MyObject
{
Id = 3,
Name = "Mary"
},
new MyObject
{
Id = 4
}
};
var objects = new MyObjectLists(list);
foreach (MyObject myObject in objects.NonNullNameObjects)
{
Console.WriteLine($"Object with Id {myObject.Id} has a non-null name");
}
foreach (MyObject myObject in objects.NullNameObjects)
{
Console.WriteLine($"Object with Id {myObject.Id} has a null name");
}
answered Nov 21 '18 at 9:16
Rui JarimbaRui Jarimba
7,12063158
7,12063158
add a comment |
add a comment |
I think you're looking for something like this example:
class MyObject
{
int id;
string name;
}
var objectList = new List<MyObject>();
objectList.Add(new MyObject { name = "item 1" });
objectList.Add(new MyObject { name = string.Empty });
objectList.Add(new MyObject { name = "item 3" });
var objectsWithName = objectList.Where(x => !string.IsNullOrEmpty(x.name));
var objectsWithoutName = objectList.Except(objectsWithName);
I've created 2 lists that the first list contains the MyObject
items with the name
property is NOT null, otherwise to the second's.
Except
is too expensive here.
– Patrick Hofman
Nov 21 '18 at 9:37
@PatrickHofman I'm sorry. Could you please explain why?
– Foo
Nov 21 '18 at 9:46
1
Because it will create a hashset to compare values, while there is absolutely no need for.
– Patrick Hofman
Nov 21 '18 at 9:50
add a comment |
I think you're looking for something like this example:
class MyObject
{
int id;
string name;
}
var objectList = new List<MyObject>();
objectList.Add(new MyObject { name = "item 1" });
objectList.Add(new MyObject { name = string.Empty });
objectList.Add(new MyObject { name = "item 3" });
var objectsWithName = objectList.Where(x => !string.IsNullOrEmpty(x.name));
var objectsWithoutName = objectList.Except(objectsWithName);
I've created 2 lists that the first list contains the MyObject
items with the name
property is NOT null, otherwise to the second's.
Except
is too expensive here.
– Patrick Hofman
Nov 21 '18 at 9:37
@PatrickHofman I'm sorry. Could you please explain why?
– Foo
Nov 21 '18 at 9:46
1
Because it will create a hashset to compare values, while there is absolutely no need for.
– Patrick Hofman
Nov 21 '18 at 9:50
add a comment |
I think you're looking for something like this example:
class MyObject
{
int id;
string name;
}
var objectList = new List<MyObject>();
objectList.Add(new MyObject { name = "item 1" });
objectList.Add(new MyObject { name = string.Empty });
objectList.Add(new MyObject { name = "item 3" });
var objectsWithName = objectList.Where(x => !string.IsNullOrEmpty(x.name));
var objectsWithoutName = objectList.Except(objectsWithName);
I've created 2 lists that the first list contains the MyObject
items with the name
property is NOT null, otherwise to the second's.
I think you're looking for something like this example:
class MyObject
{
int id;
string name;
}
var objectList = new List<MyObject>();
objectList.Add(new MyObject { name = "item 1" });
objectList.Add(new MyObject { name = string.Empty });
objectList.Add(new MyObject { name = "item 3" });
var objectsWithName = objectList.Where(x => !string.IsNullOrEmpty(x.name));
var objectsWithoutName = objectList.Except(objectsWithName);
I've created 2 lists that the first list contains the MyObject
items with the name
property is NOT null, otherwise to the second's.
answered Nov 21 '18 at 9:16


FooFoo
1
1
Except
is too expensive here.
– Patrick Hofman
Nov 21 '18 at 9:37
@PatrickHofman I'm sorry. Could you please explain why?
– Foo
Nov 21 '18 at 9:46
1
Because it will create a hashset to compare values, while there is absolutely no need for.
– Patrick Hofman
Nov 21 '18 at 9:50
add a comment |
Except
is too expensive here.
– Patrick Hofman
Nov 21 '18 at 9:37
@PatrickHofman I'm sorry. Could you please explain why?
– Foo
Nov 21 '18 at 9:46
1
Because it will create a hashset to compare values, while there is absolutely no need for.
– Patrick Hofman
Nov 21 '18 at 9:50
Except
is too expensive here.– Patrick Hofman
Nov 21 '18 at 9:37
Except
is too expensive here.– Patrick Hofman
Nov 21 '18 at 9:37
@PatrickHofman I'm sorry. Could you please explain why?
– Foo
Nov 21 '18 at 9:46
@PatrickHofman I'm sorry. Could you please explain why?
– Foo
Nov 21 '18 at 9:46
1
1
Because it will create a hashset to compare values, while there is absolutely no need for.
– Patrick Hofman
Nov 21 '18 at 9:50
Because it will create a hashset to compare values, while there is absolutely no need for.
– Patrick Hofman
Nov 21 '18 at 9:50
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%2f53408452%2fwhat-is-the-simplest-way-to-partition-a-list-based-on-a-criteria%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
4
for loop with if statement would be simplest, LINQ is overhead here
– brykneval
Nov 21 '18 at 9:03
1
This would help you stackoverflow.com/questions/419019/…
– Hamza Haider
Nov 21 '18 at 9:10
@brykneval - what makes you think Linq is an overhead -- have you compared the IL generated by a foreach loop with that generated by Linq? I think you'll find they are not very different.
– Chris F Carroll
Nov 21 '18 at 9:17