c# – Linq query to merge overlapping elements

I have this class representing a period of time:

public class Period
{
    public Period(DateTime dateFrom)
    {
        DateFrom = dateFrom;
    }

    public Period(DateTime dateFrom, DateTime? dateTo)
    {
        DateFrom = dateFrom;
        DateTo = dateTo;
    }

    public Period() { }
    public DateTime DateFrom { get; set; }
    public DateTime? DateTo { get; set; }


    public bool IsOverlapping(Period other)
    {
        if (!DateTo.HasValue)
        {
            return DateFrom.Value <= other.DateTo.Value;
        }
        
        if (!other.DateTo.HasValue)
        {
            return other.DateFrom.Value <= DateTo.Value;
        }

        return DateFrom.Value <= other.DateTo.Value && other.DateFrom.Value <= DateTo.Value;
    }

    public bool IsFinite => DateTo.HasValue;

    public bool IsInfinite => !IsFinite;

    // Equals/GetHashCode have been overrided
}

Now a have a list of periods and for each of them I have to perform an network call so to minimize them I decide to merge all overlapping periods.

So a list like that :

  • 2020-01-01 -> 2020-01-10
  • 2020-02-05 -> 2020-02-10
  • 2020-02-07 -> 2020-02-15
  • 2020-02-13 -> 2020-02-20
  • 2020-03-01 -> 2020-03-10
  • 2020-03-25 -> 2020-03-31
  • 2020-03-30 ->

Should become :

  • 2020-01-01 -> 2020-01-10
  • 2020-02-05 -> 2020-02-20
  • 2020-03-01 -> 2020-03-10
  • 2020-03-25 ->

I tried this code

    periods.OrderBy(p => p.DateFrom.Value)
            .Aggregate(new List<Period>(), (ps, p) =>
            {
                if (!ps.Any())
                {
                    ps.Add(p);
                    return ps;
                }

                var last = ps.Last();
                if (last.IsOverlapping(p))
                {
                    if (last.IsInfinite || p.IsInfinite)
                    {
                        ps(ps.Count() - 1) = new Period(DateTimeHelpers.Min(last.DateFrom.Value, p.DateFrom.Value), null);
                    }
                    else
                    {
                        ps(ps.Count() - 1) = new Period(DateTimeHelpers.Min(last.DateFrom.Value, p.DateFrom.Value), DateTimeHelpers.Max(last.DateTo.Value, p.DateTo.Value));
                    }

                    return ps;
                }

                ps.Add(p);
                return ps;

            });

It’s working properly but I’m not satisfied with it so I wonder if there is a more performant/elegant/readable way to do it ?

I’m not talking about just refactoring to extract some methods but a fundamentally different solution, it’s possible I missed a useful LINQ operator.

Here is my test if you want to reproduce it (MsTest + FluentAssertions). The period are not in the right order to ensure it will be take care of by the method itself:

        // Arrange
        var periods = new List<Period>()
        {
            new Period(new DateTime(2020, 2, 13), new DateTime(2020, 2, 20)),
            new Period(new DateTime(2020, 3, 1), new DateTime(2020, 3, 10)),
            new Period(new DateTime(2020, 3, 25), new DateTime(2020, 3, 31)),
            new Period(new DateTime(2020, 3, 30)),
            new Period(new DateTime(2020, 1, 1), new DateTime(2020, 1, 10)),
            new Period(new DateTime(2020, 2, 5), new DateTime(2020, 2, 10)),
            new Period(new DateTime(2020, 2, 7), new DateTime(2020, 2, 15))
        };

        // Act
        var mergedPeriods = Implementation(periods);

        // Assert
        mergedPeriods.Should().HaveCount(4);
        mergedPeriods(0).Should().Be(new Period(new DateTime(2020, 1, 1), new DateTime(2020, 1, 10)));
        mergedPeriods(1).Should().Be(new Period(new DateTime(2020, 2, 5), new DateTime(2020, 2, 20)));
        mergedPeriods(2).Should().Be(new Period(new DateTime(2020, 3, 1), new DateTime(2020, 3, 10)));
        mergedPeriods(3).Should().Be(new Period(new DateTime(2020, 3, 25)));

C# – Linq – Techniques for avoiding repeating same pieces of code

I am writing a piece of code for C# Web Api, letting the clients to pass a column name and sort direction as parameter.
Although there are, like, 30-ish properties, so the following code (despite it works) gets ugly after a while.

What are my options to avoid repeating this seemingly same pieces of code?

if (column == nameof(MyModel.ColumnA).ToLower())
{
    if (parameters.IsOrderByAsc)
    {
        return queryResult.OrderBy(q => q.ColumnA);
    }

    return queryResult.OrderByDescending(q => q.ColumnA);
}

if (column == nameof(MyModel.ColumnB).ToLower())
{
    if (parameters.IsOrderByAsc)
    {
        return queryResult.OrderBy(q => q.ColumnB);
    }

    return queryResult.OrderByDescending(q => q.ColumnB);
}

if (column == nameof(MyModel.ColumnC).ToLower())
{
    if (parameters.IsOrderByAsc)
    {
         return queryResult.OrderBy(q => q.ColumnC);
    }

    return queryResult.OrderByDescending(q => q.ColumnC);
}

....


```

sharepoint online – How to filter Multichoice column from ListitemCollection using LINQ

I want to filter the Multi choice field values using LINQ. I want to use the not contains to filter the List item, Since Not contains is not there in CAML query, i am using Linq to filter the not contains in ListItemcollection.

Want to filter all the lisitems which doesn’t contains “.net” value from the multi choice field using linq.

Any help would be appreciated. Thanks in Advance

c# – Create a method in a Cosmos service that runs a LINQ lambda passed as parameter

I’m creating a Cosmos service, it has basic CRUD but I want to implement one method that receiving an expression with LINQ executes it against the DB. I have this:

public IOrderedQueryable<T> GetLinqQueryable<T>(string partitionKeyFilter = null)
{
    var container = GetContainer<Game>();
    QueryRequestOptions queryRequestOptions = null;

    if (partitionKeyFilter != null)
    {
        queryRequestOptions = new QueryRequestOptions()
        {
            PartitionKey = new PartitionKey(partitionKeyFilter),
        };
    }

    return container.GetItemLinqQueryable<T>(requestOptions: queryRequestOptions);
}

public async Task<IList<T>> GetQueryResultsAsync<T>(IQueryable<T> query)
{
    var result = new List<T>();

    using var iterator = query.ToFeedIterator();
    while (iterator.HasMoreResults)
    {
        var response = await iterator.ReadNextAsync();
        result.AddRange(response);
    }

    return result;
}

But it implies that I have to call in two lines or like this:

var results = await _cosmosService.GetQueryResultAsync(_cosmosService.GetLinqQueryable<T>().Where(x => x.Id == 1));šŸ¤¢

Can this be improved somehow? Maybe extension methods or anything?

What makes LINQ (C#) unique compared to another DSL such as Django query syntax?

My question to the community is this:

What makes C#’s LINQ Unique from other query language in other languages and frameworks, or does it not have anything to make it unique at this point?

Specifically with regard to Django or Laravel, but that doesn’t matter all that much. I’m not looking for an opinion of why someone might like it more but rather if there is any concrete difference between them that a general developer would be inclined to choose one over the other because of that difference.

Thoughts

Before I posted this I found this SE post (Python Unique Characteristics), that talks about it may be rather hard to find something that is actually unique. Which is a valid point, however the reason I ask is because I know a lot of .NET developers that use LINQ as a main selling point of .NET (myself included). However, when thinking about it more in depth I don’t know if it is a valid argument anymore which is more what I’m trying to accomplish with this question.

What follows is context

My coworker and I were debating on the reason why LINQ (in the context of C#) could be an argument to use C# over another language. Especially when it can be compared to other DSLs like it (At least I believe it’s a kind of DSL, could be wrong though). We could not actually think of any concrete reason why LINQ would have any distinct advantage, feature or unique oddity over any other query syntax in a modern language or framework. The closest I could come up with was that you could write an underlying driver for LINQ to allow it to theoretically work with just about any data system out there, but the argument could me made that other languages support stuff like that as well.

Part of this question is due to an on going internal discussion between our devs about the merits of C# vs Django, but that is an entirely other area not for the scope of this question.

General Information

The following are some locations where I have been looking to try and find information at least from more official sources.

vb.net – Use LINQ to Group data from data table

I have a linq question. I want to use LINQ to group data from a DataTable (columns: RUN_NAME,H_YYYY,H_MM,H_MON).

The data looks like this:

RUN_NAME H_YYYY H_MM H_MON
2019-1 2019 1 Jan
2019-1 2019 2 Feb
2019-1 2019 3 Mar
2019-1 2019 4 Apr
2019-2 2019 5 May
2019-2 2019 6 Jun
2019-2 2019 7 Jul
2019-2 2019 8 Aug
2019-3 2019 9 Sep
2019-3 2019 10 Oct
2019-3 2019 11 Nov
2019-3 2019 12 Dec

I need something like this in the result:
2019-1
2019 1 Jan
2019 2 Feb
2019 3 Mar
2019 4 Apr
2019-2
2019 5 May
2019 6 Jun
2019 7 Jul
2019 8 Aug
2019-3
2019 9 Sep
2019 10 Oct
2019 11 Nov
2019 12 Dec

Here is what I have tried so far:
”’
CalendarMonthList = (From rw As DataRow In dt.Rows Select New CalendarMonth With {
.Run_Name=CheckStringNull(rw(“run_name”).ToString),
.Month_Scope = (From r In dt.AsEnumerable Where r(“run_name”) = .Run_Name Select New MonthScope With {.h_yyyy = CheckDbNull(rw(“h_yyyy”)), .h_mm = CheckDbNull(rw(“h_mm”)), .h_mon = CheckStringNull(rw(“h_mon”).ToString)}).Distinct.ToList()}).Distinct.ToList()

”’

Convertir SQL a Linq Entity Framework con dos Tablas

Saludos en este momento tengo esta consulta que me gustaria convertir a Linq con Lambda, estoy trabajando con EF Core.

select periodoID, Nombre
from Periodo
where PeriodoID In (select periodoID from grupo where profesorID =215) -- cambiar por la variable idUsuario
order by periodoID desc; 

gracias por la atenciĆ³n espero me puedan apoyar.

c# – EF LINQ query cannot be translated

I have an app where I have run into an exception that I cannot figure out. Using EF Core 3.1 and Postgres 12.

Have the following relationships:

User -> UserNetworks -> Network -> Resource

A user belongs to many networks. A network can contain many resources. I want to query all the resources that a user has access to in all the networks they are a part of.

I have a test app built that does this and works fine. The issue is that I have a real world app that is much more complicated where the same query doesn’t work and throws the following exception:

The LINQ expression ‘DbSet.Join(outer: DbSet, inner: r => EF.Property(r, “network_id”), outerKeySelector: n => EF.Property(n, “Id”), innerKeySelector: (o, i) => new TransparentIdentifier<Resource, Network>(Outer = o, Inner = i)).Where(r => r.Inner.UserNetworks.Any(y => y.User.Id == 2))’ could not be translated.

I understand the exception and know what it means, but I haven’t been able to figure out why I am getting it in this case as it seems like it should work fine. In troubleshooting all day, I finally noticed something in the original exception that I had overlooked that seemed wrong. However, I am not sure it’s the issue or, if it is, how to fix it?

Quick backstory…since we decided to use Postgres for this project and we didn’t want to have to write all our queries with quotes everywhere, we decided to lowercase all the tables and columns. Every table and every column in the entire db is lowercase, with words separated by underscores. This is done via EF Type Configurations as seen below.

Below is a snippet of the resource type configuration class. “Builder” is just and instance of EntityTypeBuilder. The calls to HasForeignKey are simply passing string values via the GetName method call. For instance, in the example below, HasForeignKey would get passed the value of “network_id”.

Resource Type Congfiguration

   Builder
      .HasOne(x => x.Network)
      .WithMany(x => x.Resources)
      .IsRequired()
      .HasForeignKey(ResourceEnums.Columns.Network_Id.GetName());

If you look back at the exception, specifically at the “inner” and “outerKeySelector” values, you will notice that in the “inner”, the EF Property uses “network_id” (lowercase) to point at the foreign key column (like i configured it to). However, the outerKeySelector uses “Id” (uppercase) as its property name. Even though the property name in the C# entity is called Id (uppercase), I’m wondering if this outerKeySelector shouldn’t actually be the id column from the principal table and therefore, should be “id” (lowercase).

So, my question:

  1. If this is possibly the issue and since EF is generating this value (ie…not my code directly), how do I tell EF via the Type Configuration that “Id” should be “id” when used in this relationship?

HasPrincialKey seemed like a promising option, like this:

Builder
   .HasMany(x => x.Resources)
   .WithOne(x => x.Network)
   .HasPrincipalKey("id");

But when I tried it this way, the code will compile, but the EF migration tool fails when generating the migration scripts. This exception is:

“The property ‘id’ cannot be added to the type ‘Network’ because there
was no property type specified and there is no corresponding CLR
property or field. To add a shadow state property the property type
must be specified.”.

My guess on this is because the property on the model is uppercase and this is defining it as lowercase so they can’t be mapped together.

If I change the type configuration to this:

   Builder
      .HasOne(x => x.Network)
      .WithMany(x => x.Resources)
      .IsRequired()
      .HasPrincipalKey(x => x.Id)
      .HasForeignKey(ResourceEnums.Columns.Network_Id.GetName());

EF will generate the migration scripts again, but I go back to the original exception.

I am not sure what else to try at this point. Any help is greatly appreciated, and I can provide any information needed if there is anything unclear or missing.

c# – Simplifying for loops that includes conditions with better linq queries

The code below selects all items that are locked. How can I optimise it?
ShopItemData doesn’t contain a field for locked/unlocked.

_allItems is a ShopItemData()

_codaCommonShopItems is a CodaShopItem()

_codaRareShopItems is a CodaShopItem()

_codaEpicShopItems is a CodaShopItem()

public class CodaShopItem : MonoBehaviour
    {
        private Button _itemButton;
        private bool _inUse;
        private int _itemId;
        private CodaShopScreen.ItemRarity _itemRarity;

        public int ItemId => _itemId;
        public bool Unlocked;
        public bool InUse => _inUse;
        public CodaShopScreen.ItemRarity ItemRarity => _itemRarity;
}

public class ShopItemData : ScriptableObject
    {
        public int ItemId;
        public Sprite ItemSprite;
        public CodaShopScreen.ItemRarity ItemRarity;
        public GameObject InGamePrefab;
        public GameObject PreviewPrefab;
    }


public IEnumerable<ShopItemData> GetLockedItems()
        {
            var lockedCommonItems = _codaCommonShopItems.Where(item => !item.Unlocked).ToArray();
            var lockedRareItems = _codaRareShopItems.Where(item => !item.Unlocked).ToArray();
            var lockedEpicItems = _codaEpicShopItems.Where(item => !item.Unlocked).ToArray();
            var allLockedItems = new List<ShopItemData>();
            var allItemDatas = GetAllItems().ToArray();
            
            for (var i = 0; i < lockedCommonItems.Length; i++)
            {
                var lockedItemData = allItemDatas.First(item => item.ItemId == lockedCommonItems(i).ItemId && item.ItemRarity == lockedCommonItems(i).ItemRarity);
                allLockedItems.Add(lockedItemData);
            }
            
            for (var i = 0; i < lockedRareItems.Length; i++)
            {
                var lockedItemData = allItemDatas.First(item => item.ItemId == lockedRareItems(i).ItemId && item.ItemRarity == lockedRareItems(i).ItemRarity);
                allLockedItems.Add(lockedItemData);
            }
            
            for (var i = 0; i < lockedEpicItems.Length; i++)
            {
                var lockedItemData = allItemDatas.First(item => item.ItemId == lockedEpicItems(i).ItemId && item.ItemRarity == lockedEpicItems(i).ItemRarity);
                allLockedItems.Add(lockedItemData);
            }

            return allLockedItems;
        }

public IEnumerable<ShopItemData> GetAllItems()
        {
            return _allItems;
        }

c# – LINQ Hacer un contains con un string en una fecha

tengo un buscador donde el usuario mete un string y despues se hace un contains a cada columna en la base de datos.

dbContext.Usuario.Where(c=> 
   c.Nombre.Contains(filto) ||
   c.Apellido.Contains(filto) ||
   c.FechaNacimiento.ToString("yyyy/MM/dd").Contains(filto)
)

Pero al hacer “Datetime.ToString(“yyyy/MM/dd”).Contains(filtro)” falla porque LINQ no lo puede traducir.
Y la busqueda puede ser ‘2002/12/28′ o ’01/07’ o ‘manolo’ o ’21’ o cualquier cosa