Ok, I have a List<> of objects (which the object contains multiple properties) and I would like to use a LINQ function to transform the List<> to List based on a conditional statement that compares TWO elements at a time. Is this possible?
I tried searching on google but couldn't find it.
Edit: Ok everyone, my apologize I didn't add code. No need to get angry at me :D
Here's some code
var words = apiResult
.Skip(1)
.OrderBy(x => x.BoundingPoly.Vertices[0].Y)
// add here a LINQ statement
.ToList();
apiResult is IReadOnlyList of EntityAnnotation
var apiResult = client.GetText(image);
After I ordered the list according to the Y axis I want to concat words (strings) as a sentence according to the Y axis so that the "words" list will transform into sentences.
For example, if I have three elements in the list such as
{ text: 'Hi', Y: 22 }
{ text: 'There!', Y: 22 }
{ text: 'Bye!', Y: 57 }
it will transform into
{ text: 'Hi There!', Y: 22 }
{ text: 'Bye!', Y: 57 }
CodePudding user response:
I used a simplified model with tuples, since I do not have these EntityAnnotations. The tuples consist of a text and a Y value. You will have to adapt this to your real data model.
First, I group by the Y value. Then I order the groups by the Key which contains this Y value.
The groups are an enumeration of the grouped elements. So, for each group I select the texts and join them to form a sentence and create a tuple together with the Y value.
// Sample data using tuples.
(string text, int Y)[] apiResult = {
("Hi", 22),
("There", 22),
("Bye", 57),
};
var words = apiResult
.GroupBy(a => a.Y) // Use: a.BoundingPoly.Vertices[0].Y
.OrderBy(g => g.Key)
.Select(g => (text: String.Join(' ', g.Select(w => w.text).ToArray()), Y: g.Key));
foreach (var word in words) {
Console.WriteLine(word);
}
Prints:
(Hi There, 22)
(Bye, 57)
CodePudding user response:
Is this what you after?
var list = new List<ApiResult> { new ApiResult { text = "Hi", Y = 22 } , new ApiResult { text = "There !", Y = 22 } , new ApiResult { text = "Bye!", Y = 57 } };
var result = list.GroupBy(x => x.Y).Select(x => new
{
text = x.Select(y => y.text),
Y = x.Key
});
CodePudding user response:
Yes!
Here is an example comparing numbers to the next number in the sequence:
List<int> numbers = new List<int> { 1, 2, 3 };
var numbersGreaterThanNext = numbers.Where(x => x != numbers.Last()
&& x > numbers.ElementAt(numbers.IndexOf(x) 1)).ToList();
var numbersSmallerThanNext = numbers.Where(x => x != numbers.Last()
&& x < numbers.ElementAt(numbers.IndexOf(x) 1)).ToList();
Console.WriteLine($"Numbers greater than next number in sequence: {numbersGreaterThanNext.Count}");
Console.WriteLine($"Numbers smaller than next number in sequence: {numbersSmallerThanNext.Count}");