
LINQ to Objects is a feature of .NET that allows developers to query in-memory data structures such as lists, arrays, and collections using LINQ syntax. Here's an example of using LINQ to query a JSON object in C#:
Suppose we have the following JSON object:
{
"fruits": [
{ "name": "apple", "color": "red" },
{ "name": "banana", "color": "yellow" },
{ "name": "orange", "color": "orange" }
]
}
We can parse the JSON string into a JObject using the Newtonsoft.Json NuGet package:
using Newtonsoft.Json.Linq;
var jsonString = "{\"fruits\":[{\"name\":\"apple\",\"color\":\"red\"},{\"name\":\"banana\",\"color\":\"yellow\"},{\"name\":\"orange\",\"color\":\"orange\"}]}";
var jsonObject = JObject.Parse(jsonString);
Now we can use LINQ to query the "fruits" array:
var fruits = jsonObject["fruits"].Select(f => new { Name = f["name"], Color = f["color"] });
foreach (var fruit in fruits)
{
Console.WriteLine($"{fruit.Name} is {fruit.Color}");
}
The output will be:
apple is red
banana is yellow
orange is orange
In this example, we used LINQ to select the "name" and "color" properties of each fruit object in the "fruits" array and created a new anonymous type with those properties. Then, we looped through the result and printed the name and color of each fruit.
Here's a more complex example of using LINQ to Objects with a list of custom objects:
Suppose we have the following class representing a book:
public class Book
{
public string Title { get; set; }
public string Author { get; set; }
public int PublicationYear { get; set; }
public double Price { get; set; }
}
And suppose we have a list of books:
var books = new List<Book>
{
new Book { Title = "The Great Gatsby", Author = "F. Scott Fitzgerald", PublicationYear = 1925, Price = 12.99 },
new Book { Title = "To Kill a Mockingbird", Author = "Harper Lee", PublicationYear = 1960, Price = 9.99 },
new Book { Title = "1984", Author = "George Orwell", PublicationYear = 1949, Price = 8.99 },
new Book { Title = "Pride and Prejudice", Author = "Jane Austen", PublicationYear = 1813, Price = 6.99 },
new Book { Title = "The Catcher in the Rye", Author = "J.D. Salinger", PublicationYear = 1951, Price = 7.99 },
new Book { Title = "Animal Farm", Author = "George Orwell", PublicationYear = 1945, Price = 5.99 },
new Book { Title = "The Hobbit", Author = "J.R.R. Tolkien", PublicationYear = 1937, Price = 10.99 },
new Book { Title = "The Lord of the Rings", Author = "J.R.R. Tolkien", PublicationYear = 1954, Price = 22.99 }
};
We can use LINQ to Objects to perform various operations on the list of books. Here are a few examples:
Find all books by George Orwell:
var orwellBooks = books.Where(b => b.Author == "George Orwell");
foreach (var book in orwellBooks)
{
Console.WriteLine($"Title: {book.Title}, Author: {book.Author}, Publication Year: {book.PublicationYear}, Price: {book.Price}");
}
Output:
Title: 1984, Author: George Orwell, Publication Year: 1949, Price: 8.99
Title: Animal Farm, Author: George Orwell, Publication Year: 1945, Price: 5.99
Find the average price of all books:
var averagePrice = books.Average(b => b.Price);
Console.WriteLine($"Average price: {averagePrice:C}");
Output:
Average price: $10.87
Find the most expensive book:
var mostExpensiveBook = books.OrderByDescending(b => b.Price).First();
Console.WriteLine($"Most expensive book: {mostExpensiveBook.Title} ({mostExpensiveBook.Author}), {mostExpensiveBook.Price:C}");
Output:
Most expensive book: The Lord of the Rings (J.R.R. Tolkien), $22.99
Group books by author:
var booksByAuthor = books.GroupBy(b => b.Author);
foreach (var group in booksByAuthor)
{
Console.WriteLine($"Author: {group.Key}");
foreach (var book in group)
{
Console.WriteLine($" Title: {book.Title}, Publication Year: {book.PublicationYear}, Price: {book.Price:C}");
}
}
Output:
Author: F. Scott Fitzgerald
In summary, LINQ to Objects is a powerful feature of .NET that allows developers to query in-memory data structures such as lists, arrays, and collections using LINQ syntax. With LINQ to Objects, you can easily perform operations such as filtering, sorting, grouping, and aggregation on your data. It is a convenient way to work with complex data structures and can save you a lot of time and effort. In this example, we demonstrated how to use LINQ to Objects with a list of custom objects representing books, and showed how to perform various operations such as filtering by author, finding the average price, finding the most expensive book, and grouping by author.
About the Creator
Bharath S
From Oddanchatram, Tamil Nadu, India




Comments
There are no comments for this story
Be the first to respond and start the conversation.