C
C#16mo ago
Alex Frost

❔ Get list of indices from a List

I have a result set called "result". I want to use Linq to get a list of distinct items by name and their indices in the source resultset. How can I accomplish that?
15 Replies
ero
ero16mo ago
how would this work? first of all, a set already only contains distinct items. if you mean that you have a list, and you then got the items distinct by their name, which distinct item's index would you want? the first? second? nth?
dotnut
dotnut16mo ago
Something like collection.DistinctBy(item => item.Name).Select(item, index => new { Name = item.Name, Index = index})
ero
ero16mo ago
but that's incorrect that would return the index in the new distinct collection
string[] foo =
{
"Foo",
"Foo",
"Bar",
"Bar"
};
string[] foo =
{
"Foo",
"Foo",
"Bar",
"Bar"
};
like what would the result look like here?
dotnut
dotnut16mo ago
I think they mean collection
ero
ero16mo ago
?
dotnut
dotnut16mo ago
Just because of the mentioning of Distinct
ero
ero16mo ago
what about it
dotnut
dotnut16mo ago
You said it already a set would have distinct items Hence I believe they just meant a collection of things
ero
ero16mo ago
sure doesn't really matter your version would be incorrect in any case
their indices in the source resultset
this part just doesn't really make sense
dotnut
dotnut16mo ago
Ah good point Yeah it doesnt 😅
ero
ero16mo ago
it's fine that they want the index in the source collection, but if you expect the item to exist more than once, then you need to have a concept of which one you want
dotnut
dotnut16mo ago
Exactly
Alex Frost
Alex FrostOP16mo ago
Hi, thank you for the guidence. I was able to work it out following what was said and some search:
distinctItems = result.Select((value, index) => new { index, value.PropertyID })
.DistinctBy(p => p.PropertyID)
.ToDictionary(x => x.index, x => x.PropertyID);
distinctItems = result.Select((value, index) => new { index, value.PropertyID })
.DistinctBy(p => p.PropertyID)
.ToDictionary(x => x.index, x => x.PropertyID);
ero
ero16mo ago
i mean again like, it's not really clear if this is the desired solution either way you should prefer using a valuetuple
results
.Select((r, i) => (Id: r.PropertyId, Index: i))
.DistinctBy(t => t.Id)
.ToDictionary(t => t.Index, t => t.Id);
results
.Select((r, i) => (Id: r.PropertyId, Index: i))
.DistinctBy(t => t.Id)
.ToDictionary(t => t.Index, t => t.Id);
Accord
Accord16mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server